从 char(不是 char*)到 std::string 的首选转换

2022-01-12 00:00:00 string char type-conversion c++

我有一个 char,一个普通的旧字符,我想把它变成一个 std::string.std::string(char) 当然不存在.我可以创建一个 char 数组并将其复制进去,我可以通过字符串流,或许多其他小的迂回路线.目前,我更喜欢 boost::lexical_cast,但对于这个简单的任务来说,即使这样也显得过于冗长.那么首选的方式是什么?

I have a char, a plain old character, that I would like to turn into an std::string. std::string(char) doesn't exist of course. I could create an char array and copy it in, I could go through string streams, or many other little roundabout routes. Currently, I prefer boost::lexical_cast, but even that seems too verbose for this simple task. So what's the preferred way?

推荐答案

std::string 有一个接受数字和字符的构造函数.字符将重复给定的次数.因此,您应该使用:

std::string has a constructor that takes a number and a character. The character will repeat for the given number of times. Thus, you should use:

std::string str(1, ch);

相关文章