简体   繁体   English

如何将字符串转换为由 c++ 中的字符组成的字符串数组?

[英]How to convert a string to array of strings made of characters in c++?

How to split a string into an array of strings for every character ?如何将字符串拆分为每个字符的字符串数组? Example:例子:

INPUT:
string text = "String.";

OUTPUT:
["S" , "t" , "r" , "i" , "n" , "g" , "."]

I know that char variables exist, but in this case, I really need an array of strings because of the type of software I'm working on.我知道存在 char 变量,但在这种情况下,由于我正在使用的软件类型,我确实需要一个字符串数组

When I try to do this, the compiler returns the following error:当我尝试这样做时,编译器返回以下错误:

Severity    Code    Description Project File    Line    Suppression State
Error (active)  E0413   no suitable conversion function from "std::string" to "char" exists 

This is because C++ treats stringName[index] as a char , and since the array is a string array , the two are incopatible.这是因为C++stringName[index]视为char ,并且由于数组字符串数组,因此两者不兼容。 Here's my code:这是我的代码:

string text = "Sample text";
string process[10000000];

for (int i = 0; i < sizeof(text); i++) {
    text[i] = process[i];
}

Is there any way to do this properly?有没有办法正确地做到这一点?

If you are going to make string, you should look at the string constructors .如果要制作字符串,则应查看字符串构造函数 There's one that is suitable for you (#2 in the list I linked to)有一个适合你(我链接到的列表中的#2)

for (int i = 0; i < text.size(); i++) {
    process[i] = string(1, text[i]); // create a string with 1 copy of text[i]
}

You should also realise that sizeof does not get you the size of a string Use the size() or length() method for that.您还应该意识到sizeof不会让您获得字符串的大小 使用size()length()方法。

You also need to get text and process the right way around, but I guess that was just a typo.您还需要以正确的方式获取textprocess ,但我想这只是一个错字。

std::string is a container in the first place, thus anything that you can do to a container, you can do to an instance of std::string . std::string首先是一个容器,因此您可以对容器执行的任何操作,都可以对std::string的实例执行。 I would get use of the std::transform here:我会在这里使用std::transform

const std::string str { "String." };
std::vector<std::string> result(str.size());
std::transform(str.cbegin(), str.cend(), result.begin(), [](auto character) {
    return std::string(1, character);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM