How to Iterate through a String word by word in C++
Given a String comprising of many words separated by space, the task is to iterate over these words of the string in C++.
Example:
Input: str = “GeeksforGeeks is a computer science portal for Geeks”
Output: GeeksforGeeks
is
a
computer
science
portal
for
Geeks
Input: str = “Geeks for Geeks”
Output: Geeks
for
Geeks
Approach: istringstream class is best suitable for this purpose. When a string is given split by whitespace, this class can be used to easily fetch and use each word of the String.
Syntax:
string str = {"Geeks for Geeks"};
istringstream iss(str);
Below is the implementation of the above approach:
CPP
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
string str = "GeeksforGeeks is a computer "
"science portal for Geeks" ;
istringstream iss(str);
do {
string subs;
iss >> subs;
cout << subs << endl;
} while (iss);
return 0;
}
|
Output
GeeksforGeeks
is
a
computer
science
portal
for
Geeks
Another method: This can also be done iteratively
- Calculate the length of the given string say n
- Iterate on given string from i = 0 to i < n
- Check if current character str[i] == ” ” or i == n – 1
- Print the string formed by word and empty the word string
- Otherwise, keep appending characters in the word string
Below is the implementation of the
C++
#include <bits/stdc++.h>
using namespace std;
void splitWord(string str)
{
int n = str.length();
string word = "" ;
for ( int i = 0; i < n; i++) {
if (str[i] == ' ' or i == (n - 1)) {
cout << word + str[i] << endl;
word = "" ;
}
else {
word += str[i];
}
}
}
int main()
{
string str = "GeeksforGeeks is a computer "
"science portal for Geeks" ;
splitWord(str);
return 0;
}
|
Output
GeeksforGeeks
is
a
computer
science
portal
for
Geeks
Time Complexity: O(n), Where n is the size of the given string
Auxiliary Space: O(1)
Last Updated :
15 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...