0

the user should input something like this string "[1 -2.5 3;4 5.25 6;7 8 9.12]"

and i want to cut it to be like only the numbers in it so it appears like this 1 -2.5 3 4 5.25 6 7 8 9.12

well i've tried the code below but it doesn't seem to work

    string cutter(string s){
        string cuttedstring="";
        string fullstring="";

        for(int i=0; i <= s.length(); i++ ){

            if(s.at(i)!= "[" && s.at(i)!= "]" && s.at(i)!= ";"){

                for(int j=i; j<15 ; j++ ){
                    do{
                        cuttedstring += s.at(j);
                     }
                    while(s.at(j)!= " ");

                    fullstring = cuttedstring + " " ;
                    cuttedstring = "";
                }
            }
        }
        return fullstring;
    }
  • 1
    This code doesn't make much sense. First of all, the loop `do { cuttedstring += s.at(j); } while(s.at(j)!= " ");` is endless, because the variable `j` isn't changed in it. – Konstantin Murugov Apr 28 '19 at 17:36
  • it will store every number in cuttedstring and it will now the number is ended when it faces a space and then all cutted numbers will be put together in full string – Yusuf Sameh Apr 28 '19 at 17:42
  • Are you sure you don't need to remove others characters like comma or whatever? Do you want to convert multiple spaces into one? – Konstantin Murugov Apr 28 '19 at 17:42
  • i want to put these numbers in an array so i need them seperated so for now i just want to make sure they are cutted properly and i will convert them to a float and save it in an array – Yusuf Sameh Apr 28 '19 at 17:44
  • i don't know why i get an error on the first if statement – Yusuf Sameh Apr 28 '19 at 17:46

1 Answers1

0

You can use the replace method of the string class like this:

#include <algorithm>
#include <string>

int main() {
  std::string s = "example string";
  std::replace( s.begin(), s.end(), 'x', 'y');
}

But if you want to replace more than one character you can use this method.

std::string ReplaceAll(std::string str, const std::string& from, const std::string& to) {
    size_t start_pos = 0;
    while((start_pos = str.find(from, start_pos)) != std::string::npos) {
        str.replace(start_pos, from.length(), to);
        start_pos += to.length(); // Handles case where 'to' is a substring of 'from'
    }
    return str;
}

If found it on this page.

flaxel
  • 4,173
  • 4
  • 17
  • 30