Click here to Skip to main content
15,891,253 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Please Help
The title says it all
How can i print the first word of a string

What I have tried:

Nothing, don't know The title
Just need some help here
Posted
Updated 11-Nov-18 11:02am

First, decide what makes a word "end"? It is a space? Well yes - but the first word of this reply doesn't end with one, and neither does the last word of this sentence! Or this. (And this one doesn't start with a word.) 3 of the sentences in this paragraph don't!

So start by deciding what defines a "word": 'a sequence of upper- and / or lower- case letters that end with a non-alphabetic character'

With that sorted, parse your string: ignore anything that isn't a letter, then start your word. It's a word until you reach a non-letter character, and you can then print it.

Give it a try - this isn't difficult if you think about it for a few minutes.
Hint: start by writing a function that takes a character as a parameter, and returns true or false depending on if it's a "word character" or not.
 
Share this answer
 
It really depends on the exact definition of 'word' in your requirements. For simple scenarios a istringstream is just enough:
C++
#include <iostream>
#include <sstream>
using namespace std;

int main()
{
  string str = "foo bar foobar";
  istringstream iss(str);
  string first_word;
  iss >> first_word;
  cout << "first word of '" << str << "' is '" << first_word << "'" << endl;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900