Home > database >  How to convert a string to array of strings made of characters in c ?
How to convert a string to array of strings made of characters in c ?

Time:07-25

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.

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. 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?

CodePudding user response:

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)

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.

You also need to get text and process the right way around, but I guess that was just a typo.

CodePudding user response:

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. I would get use of the std::transform here:

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);
});
  • Related