-4

I am trying to process a string with a random size, and modify all numbers surrounded by certain patterns. For example,

string oldstring = "res 0.25 cap 0.12 tra 1 res 0.3 cap"; string newstring = "res 0.50 cap 0.12 tra 1 res 0.6 cap";

So all the numbers between "res" and "cap" were multiplied by 2. I only know how to search for a particular substring (using stringstream, token, while loop and getline), but I am not sure how to search for a pattern like "res ... cap" and modify the number between them.

Could anyone give me some guidance?

HumbeCoder
  • 33
  • 2

1 Answers1

1

You can try this:

int main()
{

  string s = "res 0.25 cap 0.12 tra 1 res 0.3 cap";
  vector<string>split_string;
  string current;
  for (int i = 0; i < s.length(); i++)
  {
     if (s[i] != ' ')
     {
        current += s[i];
     }
     else
     {
        split_string.push_back(current);
        current = "";
     }
  }

  vector<string>final_data;
  for (string i:split_string)
  {
     if (i.find('.') != string::npos)
     {
       double new_val = stod(i);
       double new_val1 = new_val*2;
       string final_val = to_string(new_val1);
       final_data.push_back(final_val);

     }
     else
     {
       final_data.push_back(i);
     }
   }

   string final_string;
   for (string i: final_data)
   {
      final_string += i;
      final_string += " ";
   }
  cout << final_string << endl;

  }

}

Final Output:

res 0.500000 cap 0.240000 tra 1 res 0.600000
Ajax1234
  • 69,937
  • 8
  • 61
  • 102