3

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?

12
  • 1
    Shouldn't the code example use process[i] = text[i], assuming that text is your input string you want to chop up in the way you describe..? Commented Jul 24, 2022 at 13:45
  • 1
    Another code issue, you can't use sizeof() to get the length of string as number of characters, you need to call str.length() Commented Jul 24, 2022 at 13:46
  • 1
    @saxbophone I totally agree. Meant it as a side note (and updated my comment accordingly). Commented Jul 24, 2022 at 13:50
  • 1
    The sub problem that you need to solve is how to create an object of type std::string that holds a single character. When you’ve got that, repeat until done. Commented Jul 24, 2022 at 13:50
  • 3
    It doesn't really help to start with the problem you are not trying to solve, but anyway reopened, the duplicate was incorrect. Commented Jul 24, 2022 at 14:03

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.