-4

I am trying to write a function that will split a string based on a given character and return a vector of the resulting strings but I am getting a compilation error at the line of my for loop. Any ideas why? I should be able to assign astring[0] to a char pointer correct?

/*
splits string by a given character and returns a vector of each segment
if string = "ab cd ef" and split_char = " " it will return a vector with
"ab" in first location "cd" in second location and "ef" in third location
*/
vector<string> split_string(string string_to_split, const char split_char)
{
    //deletes leading split characters
    int num_leading_split_char = 0;

    for (char * c = string_to_split[0]; c* == split_char; c++)
    {
        num_leading_split_char++;
    }

    string_to_split.erase(0, num_leading_split_char);


    //makes the split string vector
    vector<string> split_string;
    string temp_string = "";

    for (char * c = string_to_split[0]; c*; c++)
    {
        if (*c == split_char)
        {
            split_string.push_back(temp_string); //add string to vector
            temp_string = ""; //reset temp string
        }
        else
        {
            temp_string += *c; //adds char to temp string
        }
    }

    return split_string;
}

error message:

pgm5.cpp: In function ‘std::vector > split_string(std::__cxx11::string, char)’:

pgm5.cpp:257:34: error: invalid conversion from ‘__gnu_cxx::__alloc_traits >::value_type {aka char}’ to ‘char*’ [-fpermissive] for (char c = string_to_split[0]; c == split_char; c++) ^

pgm5.cpp:257:40: error: expected primary-expression before ‘==’ token for (char c = string_to_split[0]; c == split_char; c++) ^~

pgm5.cpp:269:34: error: invalid conversion from ‘__gnu_cxx::__alloc_traits >::value_type {aka char}’ to ‘char*’ [-fpermissive] for (char c = string_to_split[0]; c; c++) ^

pgm5.cpp:269:39: error: expected primary-expression before ‘;’ token
for (char c = string_to_split[0]; c; c++) ^

Compilation failed.

Vishaal Shankar
  • 1,648
  • 14
  • 26
R. Binter
  • 221
  • 1
  • 8
  • 2
    Consider reading a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282). Don't take random guesses at what is correct, it won't help – Passer By Mar 06 '18 at 03:41
  • 1
    @PasserBy looks like someone was taught pointers and C-style strings way too early. – eesiraed Mar 06 '18 at 04:37

2 Answers2

0

I should be able to assign std::string str[0] to a char* pointer correct?

No. str[0] is a char literal not a char* pointer. Your complier is giving you this exact error. Since you're already using std::string why not just simply leverage some of the nice operations it provides for you like substr and find so you don't need to reinvent the wheel or maybe it's a flat tire in your case (kidding). Also, it's a good idea to pass non-POD types that you're not modifying as const references to avoid unnecessary copies i.e. const std::string &. I know in your code there is an erase operation, but in this example there is no need to modify the string being passed in.

std::vector<std::string> split_string(const std::string &string_to_split, char delim)
{
    std::vector<std::string> results;
    size_t match = 0;
    size_t found = 0;
    // match each part of string_to_split on delim and tokenize into results
    // if delim char is never found then return empty vector
    while ((found = string_to_split.find(delim, match)) != std::string::npos)
    {
        results.push_back(string_to_split.substr(match, found - match));
        match = found + 1; // start again at next character
    }
    // after the loop, if any match was found store the last token
    if (match != 0)
    {
        results.push_back(string_to_split.substr(match));
    }
    return results;
}

If you are tokenizing on spaces you can use it like this.

std::string test("This is a test.");
std::vector<std::string> tokenized = split_string(test, ' ');
for (const auto& s : tokenized)
{
    std::cout << "s=" << s << std::endl;
}

Which will yield the following results.

 s=This
 s=is
 s=a
 s=test.
Justin Randall
  • 2,243
  • 2
  • 16
  • 23
0

Try this you can try it at http://cpp.sh/8r6ze:

#include <sstream>      // std::istringstream
#include <string>
#include <vector>
#include <iostream>


std::vector<std::string> split_string(const std::string string_to_split, 
const char delimiter)
{
   std::vector<std::string> tokens;
   std::string token;
   std::istringstream tokenStream(string_to_split);
   while (std::getline(tokenStream, token, delimiter))
   {
      tokens.push_back(token);
   }
   return tokens;
}


int main ()
{
     const std::string theString{"thy with this"};
     for (const auto &s:split_string(theString,' ')){
         std::cout << s <<std::endl;
     }
     return 0;
}
albertoCaroM
  • 46
  • 1
  • 3