+ 1
Working with strings
I have something like that: string row = "Andrew-12-Bucharest-student"; I know you can find the index of the first appearance of the "-" using row.find("-") and the last one using row.find_last_of("-"); But how can I find the indexes of the rest of "-" from my string?
3 Réponses
+ 1
String it's an object and it has methods like find() and find_last_of() which return you some result.
So, you must use following code:
int main()
{
string row = "Andrew-12-Bucharest-student";
int first = row.find("-");
int last = row.find_last_of("-");
cout << "first = " << first << endl;
cout << "lasr = " << last << endl;
return 0;
}
I'm sorry for my bad English :)
+ 1
No. I meant. How do I fid out the index of the second "-", the third "-" ans so on until the last one
your program shows me only for the last and first one.
+ 1
You just must to use a loop:
// Example program
#include <iostream>
#include <string>
using namespace std;
int main()
{
string row = "Andrew-12-Bucharest-student";
int n = 0;
while ((n = row.find("-", n)) != -1)
{
cout << n <<endl;
n++;
};
return 0;
}
Here n = row.find("-", n) mean, that you are looking for symbol "-" in variable "row" from position "n".
If result of function row,find() == -1, then we don't have more symbols in the variable "row" and we break from the loop