如何将一个字符串拆分为一个字符串数组,用于每个字符?示例:
INPUT:
string text = "String.";
OUTPUT:
["S" , "t" , "r" , "i" , "n" , "g" , "."]
我知道存在 char 变量,但在这种情况下,由于我正在使用的软件类型,我确实需要一个字符串数组。
/p>
当我尝试这样做时,编译器返回以下错误:
Severity Code Description Project File Line Suppression State
Error (active) E0413 no suitable conversion function from "std::string" to "char" exists
这是因为 C++ 将 stringName[index] 视为 char,并且由于 array 是一个字符串数组,两者不兼容。 这是我的代码:
string text = "Sample text";
string process[10000000];
for (int i = 0; i < sizeof(text); i++) {
text[i] = process[i];
}
有什么办法可以正确地做到这一点?
最佳答案
如果你要制作字符串,你应该看看string constructors .有一款适合您(在我链接的列表中排名第 2)
for (int i = 0; i < text.size(); i++) {
process[i] = string(1, text[i]); // create a string with 1 copy of text[i]
}
您还应该意识到 sizeof
不会为您提供字符串的大小!为此使用 size()
或 length()
方法。
您还需要以正确的方式获取 text
和 process
,但我想那只是一个错字。
关于c++ - 如何将字符串转换为由 C++ 中的字符组成的字符串数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73098915/