Reputation: 3
How do I separate the string into two , first one before ","or "." or " " etc and second one after that and then assign both of the to two different variables.
for example
string s="154558,ABCDEF; (This is to be inputted by the user ) string a = 154558; //It should be spilt like this after conversion string b =ABCDEF
Upvotes: 0
Views: 104
Reputation: 26
I believe it can be something as simple as using rfind + substr
size_t pos = str.rfind('.')
new_str = str.substr(0, pos);
Essentially what the code is doing is searching for the first '.' and then using substr to extract the substring.
Upvotes: 1
Reputation: 84521
The two primary ways to split the string on ','
would be (1) create a std::basic_stringstream from the string and then use std::basic_istream::getline with the delimiter of ','
to separate the two strings, e.g.
#include <iostream>
#include <string>
#include <sstream>
int main (void) {
std::string s {"154558,ABCDEF"};
std::stringstream ss(s);
std::string sub {};
while (getline (ss, sub, ','))
std::cout << sub << '\n';
}
Example Use/Output
$ ./bin/str_split_ss
154558
ABCDEF
Or the second and equally easy way would be to use std::basic_string::find_first_of and find the position of ','
within the string and then use the position with std::basic_string::substr to extract the substring on either side of the comma, e.g.
#include <iostream>
#include <string>
int main (void) {
std::string s {"154558,ABCDEF"};
size_t pos = s.find_first_of (",");
if (pos != std::string::npos) {
std::cout << "first: " << s.substr(0, pos) <<
"\nsecond: " << s.substr(pos+1) << '\n';
}
}
Example Use/Output
$ ./bin/str_split_find_first_of
first: 154558
second: ABCDEF
Either way works fine. Look things over and let me know if you have further questions.
Upvotes: 1