C++ 如何将字符附加到 std::string?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1472048/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:06:46  来源:igfitidea点击:

How to append a char to a std::string?

c++string

提问by drowneath

The following fails with the error prog.cpp:5:13: error: invalid conversion from ‘char' to ‘const char*'

以下失败并出现错误 prog.cpp:5:13: error: invalid conversion from ‘char' to ‘const char*'

int main()
{
  char d = 'd';
  std::string y("Hello worl");
  y.append(d); // Line 5 - this fails
  std::cout << y;
  return 0;
}

I also tried, the following, which compiles but behaves randomly at runtime:

我还尝试了以下内容,它可以编译但在运行时行为随机:

int main()
{
  char d[1] = { 'd' };
  std::string y("Hello worl");
  y.append(d);
  std::cout << y;
  return 0;
}

Sorry for this dumb question, but I've searched around google, what I could see are just "char array to char ptr", "char ptr to char array", etc.

对不起,这个愚蠢的问题,但我在谷歌周围搜索过,我能看到的只是“char array to char ptr”,“char ptr to char array”等。

回答by AraK

y += d;

I would use +=operator instead of named functions.

我会使用+=运算符而不是命名函数。

回答by Ferdinand Beyer

Use push_back():

使用push_back()

std::string y("Hello worl");
y.push_back('d')
std::cout << y;

回答by Patrice Bernassola

To add a char to a std::string var using the append method, you need to use this overload:

要使用 append 方法将字符添加到 std::string 变量,您需要使用此重载:

std::string::append(size_type _Count, char _Ch)

Edit : Your're right I misunderstood the size_type parameter, displayed in the context help. This is the number of chars to add. So the correct call is

编辑:您说得对,我误解了上下文帮助中显示的 size_type 参数。这是要添加的字符数。所以正确的调用是

s.append(1, d);

not

不是

s.append(sizeof(char), d);

Or the simpliest way :

或者最简单的方法:

s += d;

回答by Brian R. Bondy

In addition to the others mentioned, one of the string constructors take a char and the number of repetitions for that char. So you can use that to append a single char.

除了提到的其他人之外,其中一个字符串构造函数采用一个字符和该字符的重复次数。因此,您可以使用它来附加单个字符。

std::string s = "hell";
s += std::string(1, 'o');

回答by Hugo Zevetel

I test the several propositions by running them into a large loop. I used microsoft visual studio 2015 as compiler and my processor is an i7, 8Hz, 2GHz.

我通过将它们运行到一个大循环中来测试几个命题。我使用 microsoft visual studio 2015 作为编译器,我的处理器是 i7、8Hz、2GHz。

    long start = clock();
    int a = 0;
    //100000000
    std::string ret;
    for (int i = 0; i < 60000000; i++)
    {
        ret.append(1, ' ');
        //ret += ' ';
        //ret.push_back(' ');
        //ret.insert(ret.end(), 1, ' ');
        //ret.resize(ret.size() + 1, ' ');
    }
    long stop = clock();
    long test = stop - start;
    return 0;

According to this test, results are :

根据这个测试,结果是:

     operation             time(ms)            note
------------------------------------------------------------------------
append                     66015
+=                         67328      1.02 time slower than 'append'
resize                     83867      1.27 time slower than 'append'
push_back & insert         90000      more than 1.36 time slower than 'append'

Conclusion

结论

+=seems more understandable, but if you mind about speed, use append

+=似乎更容易理解,但如果您介意速度,请使用 append

回答by Michael Berg

Try the += operator link text, append() method link text, or push_back() method link text

尝试 += 运算符链接文本、append() 方法链接文本或 push_back() 方法链接文本

The links in this post also contain examples of how to use the respective APIs.

这篇文章中的链接还包含如何使用相应 API 的示例。

回答by Alex Spencer

the problem with:

问题在于:

std::string y("Hello worl");
y.push_back('d')
std::cout << y;

is that you have to have the 'd' as opposed to using a name of a char, like char d = 'd'; Or am I wrong?

是你必须有 'd' 而不是使用字符的名称,比如 char d = 'd'; 还是我错了?

回答by Mooing Duck

int main()
{
  char d = 'd';
  std::string y("Hello worl");

  y += d;
  y.push_back(d);
  y.append(1, d); //appending the character 1 time
  y.insert(y.end(), 1, d); //appending the character 1 time
  y.resize(y.size()+1, d); //appending the character 1 time
  y += std::string(1, d); //appending the character 1 time
}

Note that in all of these examples you could have used a character literal directly: y += 'd';.

请注意,在所有这些示例中,您都可以直接使用字符文字:y += 'd';.

Your second example almostwould have worked, for unrelated reasons. char d[1] = { 'd'};didn't work, but char d[2] = { 'd'};(note the array is size two) would have been worked roughly the same as const char* d = "d";, and a string literal canbe appended: y.append(d);.

由于无关的原因,您的第二个示例几乎会起作用。char d[1] = { 'd'};没有用,但char d[2] = { 'd'};(注意数组大小为 2)的工作方式与 大致相同const char* d = "d";,并且可以附加字符串文字:y.append(d);

回答by 2ndless

Try using the d as pointer y.append(*d)

尝试使用 d 作为指针 y.append(*d)

回答by Charles H

I found a simple way... I needed to tack a charon to a string that was being built on the fly. I needed a char list;because I was giving the user a choice and using that choice in a switch()statement.

我找到了一个简单的方法......我需要char在正在构建的字符串上钉上一根绳子。我需要一个,char list;因为我给了用户一个选择并在switch()声明中使用该选择。

I simply added another std::string Slist;and set the new string equal to the character, "list" - a, b, c or whatever the end user chooses like this:

我只是添加了另一个std::string Slist;并将新字符串设置为等于字符“列表”-a、b、c 或最终用户选择的任何内容,如下所示:

char list;
std::string cmd, state[], Slist;
Slist = list; //set this string to the chosen char;
cmd = Slist + state[x] + "whatever";
system(cmd.c_str());

Complexity may be cool but simplicity is cooler. IMHO

复杂可能很酷,但简单更酷。恕我直言