Working with strings | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
+ 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?

28th Sep 2016, 2:31 PM
Andrei Cîrpici
Andrei Cîrpici - avatar
3 ответов
+ 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 :)
28th Sep 2016, 4:13 PM
Русин Николай
Русин Николай - avatar
+ 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.
28th Sep 2016, 4:29 PM
Andrei Cîrpici
Andrei Cîrpici - avatar
+ 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
29th Sep 2016, 8:39 PM
Русин Николай
Русин Николай - avatar