如何截断字符串 [格式化] ?C++

The*_*iot 5 c++ string formatting truncate cout

我想在 cout 中截断一个字符串,

string word = "Very long word";
int i = 1;
cout << word << " " << i;
Run Code Online (Sandbox Code Playgroud)

我希望将最多 8 个字母作为字符串的输出

所以就我而言,我想要

Very lon 1
Run Code Online (Sandbox Code Playgroud)

代替 :

Very long word 1
Run Code Online (Sandbox Code Playgroud)

我不想使用 wget(8) 函数,因为不幸的是它不会将我的单词截断为我想要的大小。我也不希望“单词”字符串更改其值(我只想向用户显示单词的一部分,但将其保留在我的变量中)

提前致谢

编辑:有人发布了解决方案,它对我有用,现在我无法将他的答案标记为好,因为他在被否决后删除了他的答案。它就像使用 word.substr(0, 8) 方法一样简单。他有什么理由被否决吗?这种方法不好用吗?

Chr*_*sen 5

我知道您已经有了一个解决方案,但我认为这值得一提:是的,您可以简单地使用string::substr,但使用省略号来指示字符串已被截断是一种常见的做法。

如果这是您想要合并的内容,您可以创建一个简单的截断函数。

#include <iostream>
#include <string>

std::string truncate(std::string str, size_t width, bool show_ellipsis=true)
{
    if (str.length() > width)
        if (show_ellipsis)
            return str.substr(0, width) + "...";
        else
            return str.substr(0, width);
    return str;
}

int main()
{
    std::string str = "Very long string";
    int i = 1;
    std::cout << truncate(str, 8) << "\t" << i << std::endl;
    std::cout << truncate(str, 8, false) << "\t" << i << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出将是:

Very lon...   1
Very lon      1
Run Code Online (Sandbox Code Playgroud)

  • 我觉得省略号示例应该有一个“width-3”,否则你的截断结果会超过宽度。 (4认同)