I'm about to hit the screen with my keyboard as I couldn't convert a char to a string, or simply adding a char to a string.
我正要用键盘敲击屏幕,因为我不能将字符转换为字符串,或者只是将字符添加到字符串中。
I have an char array and I want to pick whichever chars I choose in the array to create a string. How do I do that?
我有一个char数组,我想在数组中选择任意一个chars来创建一个字符串。我该怎么做呢?
string test = "oh my F**king GOD!"
const char* charArray = test.c_str();
string myWord = charArray[0] + charArray[4];
thats how far I got with it. Please help.
这就是我用它走了多远。请帮助。
4 个解决方案
#1
1
no need to convert to c_str just:
无需转换为c_str:
string test = "oh my F**king GOD!";
string myWord;
myWord += test[0];
myWord += test[4];
#2
5
string myWord;
myWord.push_back(test[0]);
myWord.push_back(test[4]);
You don't need to use c_str()
here.
这里不需要使用c_str()。
#3
0
Are you restricted in some way to use C++ functions only? Because, for this purpose I use the old C functions like sprintf
您是否在某些方面受到限制,只能使用c++函数?因为,为了这个目的,我使用了像sprintf这样的老C函数
#4
0
You need to also need to remember that a C++ string is quite similar to a vector, while a C string is just array of chars. Vectors have an operator[]
and a push_back method. Read more here You use push_back and do not convert to c string. So your code would look like this:
您还需要记住,c++字符串与向量非常相似,而C字符串只是chars的数组。向量有一个运算符[]和一个push_back方法。在这里阅读更多内容,使用push_back,不要转换为c字符串。你的代码是这样的:
string test = "oh my F**king GOD!"
string myWord;
myWord.push_back(test[0]);
myWord.push_back(test[4]);
#1
1
no need to convert to c_str just:
无需转换为c_str:
string test = "oh my F**king GOD!";
string myWord;
myWord += test[0];
myWord += test[4];
#2
5
string myWord;
myWord.push_back(test[0]);
myWord.push_back(test[4]);
You don't need to use c_str()
here.
这里不需要使用c_str()。
#3
0
Are you restricted in some way to use C++ functions only? Because, for this purpose I use the old C functions like sprintf
您是否在某些方面受到限制,只能使用c++函数?因为,为了这个目的,我使用了像sprintf这样的老C函数
#4
0
You need to also need to remember that a C++ string is quite similar to a vector, while a C string is just array of chars. Vectors have an operator[]
and a push_back method. Read more here You use push_back and do not convert to c string. So your code would look like this:
您还需要记住,c++字符串与向量非常相似,而C字符串只是chars的数组。向量有一个运算符[]和一个push_back方法。在这里阅读更多内容,使用push_back,不要转换为c字符串。你的代码是这样的:
string test = "oh my F**king GOD!"
string myWord;
myWord.push_back(test[0]);
myWord.push_back(test[4]);