Logo

How do I iterate over the words of a string in C++?

If you’re preparing for technical interviews or looking to hone your C++ skills, learning how to split a string into words and iterate over them is a crucial foundational task. In this guide, we’ll explore multiple ways to accomplish this in C++, backed by clear explanations and sample code snippets. Whether you’re parsing user input or dealing with file data, these methods will help you handle strings seamlessly.

1. Using std::istringstream from <sstream>

One of the most straightforward methods to iterate over words is by leveraging C++ streams. The std::istringstream class treats a string like a stream of data, allowing you to easily extract tokens separated by whitespace.

#include <iostream> #include <sstream> #include <string> int main() { std::string text = "Hello world from C++"; std::istringstream iss(text); std::string word; while (iss >> word) { std::cout << word << std::endl; } return 0; }

How it works:

  • std::istringstream iss(text) creates an input string stream from text.
  • The while (iss >> word) loop extracts the next whitespace-delimited token from the stream into the word variable.
  • Each extracted token is immediately printed.

2. Using std::stringstream with Custom Delimiters

If you need to split words using a specific delimiter (not just spaces), you can use std::stringstream in a similar way. You just check the stream line by line or character by character for your custom delimiter.

#include <iostream> #include <sstream> #include <string> int main() { std::string text = "Hello,world,from,C++"; std::stringstream ss(text); std::string token; while (std::getline(ss, token, ',')) { std::cout << token << std::endl; } return 0; }

How it works:

  • std::getline(ss, token, ',') reads characters until it encounters a comma ',' or the end of the string.
  • Each extracted substring between commas is stored in token.

3. Iterating Manually Character by Character

If you want full control over how tokens are extracted (e.g., ignoring punctuation, or splitting on multiple delimiters), you can parse the string manually:

#include <iostream> #include <string> #include <cctype> int main() { std::string text = "Hello, world! from C++"; std::string word; for (size_t i = 0; i < text.size(); ++i) { char c = text[i]; if (std::isalpha(c)) { word.push_back(c); } else { // Encountered a non-alphabetic character if (!word.empty()) { std::cout << word << std::endl; word.clear(); } } } // Print the last word if any if (!word.empty()) { std::cout << word << std::endl; } return 0; }

How it works:

  • You loop through each character in text.
  • If the character is alphabetic, you append it to the current word.
  • When you encounter a separator (non-alphabetic), you print and reset the word.
  • Finally, you handle the edge case of the last token if the string doesn't end in a delimiter.

4. Using std::regex (C++11 and Above)

For more complex splitting (e.g., multiple delimiters, patterns), std::regex_token_iterator can be used. This approach is powerful but can be slower compared to simpler methods, especially for large strings.

#include <iostream> #include <string> #include <regex> int main() { std::string text = "Hello, world! from C++"; std::regex re("\\s+"); // splits on one or more whitespace characters std::sregex_token_iterator it(text.begin(), text.end(), re, -1); std::sregex_token_iterator end; for (; it != end; ++it) { std::cout << *it << std::endl; } return 0; }

How it works:

  • std::regex re("\\s+") matches one or more whitespace characters.
  • std::sregex_token_iterator iterates over the splits based on this pattern.
  • Passing -1 as the submatch parameter indicates you want the substrings between the matches (i.e., your “words”).

5. Using Custom Helper Functions

If you’ll be splitting strings in multiple places throughout your code, you can encapsulate this functionality into a helper function. For example, using an std::vector<std::string> to store each word:

#include <iostream> #include <sstream> #include <string> #include <vector> std::vector<std::string> splitByWhitespace(const std::string& text) { std::istringstream iss(text); std::vector<std::string> words; std::string word; while (iss >> word) { words.push_back(word); } return words; } int main() { std::string text = "This is a sample text"; std::vector<std::string> result = splitByWhitespace(text); for (const auto& w : result) { std::cout << w << std::endl; } return 0; }

How it works:

  • The function splitByWhitespace encapsulates the logic of using std::istringstream to tokenize by spaces.
  • You can easily modify it for other delimiters or combine it with regex to create more robust splitting utilities.

Best Practices & Common Pitfalls

  1. Always check for empty strings: If your input might be empty, handle that case gracefully to avoid unexpected behavior.
  2. Use the right tool: For simple whitespace-splitting, std::istringstream is usually the easiest. For more complex rules (multiple delimiters, ignoring punctuation, etc.), manual parsing or std::regex might be better.
  3. Avoid performance bottlenecks: Repeated string concatenations in tight loops can be costly. Optimize if dealing with large data.
  4. Mind the locale: Functions like std::isalpha or std::isspace may behave differently across locales.

Why This Is Important for Coding Interviews

String parsing is a staple question in coding interviews. Interviewers often test your ability to manipulate and process strings, as this skill is crucial for real-world software tasks such as reading log files, parsing commands, or processing user inputs. Being well-versed in multiple techniques shows your adaptability and thorough understanding of C++ fundamentals.

If you’re looking for a structured way to level up your coding interview prep, check out these resources from DesignGurus.io:

  1. Grokking the Coding Interview: Patterns for Coding Questions – Ideal for mastering the recurring coding patterns frequently tested in top tech company interviews.
  2. Grokking Data Structures & Algorithms for Coding Interviews – A deep dive into fundamental algorithms and data structures, helping you tackle complex challenges with confidence.

Where to Go Next

  • Practice: Start practicing on small problems and experiment with different splitting methods.
  • Watch Expert Tutorials: Check out the DesignGurus.io YouTube channel for free videos on coding and system design interviews.
  • Mock Interviews & Bootcamp: If you want personalized feedback, try Coding Mock Interviews with ex-FAANG engineers or enroll in their Interview Bootcamp for a structured preparation path.

Mastering string parsing is just the tip of the iceberg in preparing for interviews at top tech companies. By solidifying your fundamentals in C++, you’ll build a robust base to tackle a wide range of coding challenges. Good luck and happy coding!

CONTRIBUTOR
TechGrind