Hi there,

I have a problem in breaking a sentence into each string. i have tried to use find() to search for the " "(space), use substr to search from the first string index into the find space number. It works for the first string. But I am unable to start find the " "(space) for the second one. It makes me cant get the second string.

If there is anyone know how to solve it, please let me know. Thanks in advance.

This is my code

#include <cstring>
#include <iostream>
#include <cctype>
#include <string>

using namespace std;

int main()
{
	string *command = new string[5];
	string input;
	
	//for ex.enter my name is need_Direction
	cout << "enter something:";
	getline(cin, input);
	cout << input.size() << endl;
	cout << "user_input:" << input << endl;

	int pos = input.find(" ");
	int currPos;
	int pos2 = input.find(" ");
	
	if(pos != string::npos)
	{
		cout << "found!" << endl;
		command[0] = input.substr(0, pos);
		cout << "first string : " << command[0] << endl << endl;
		currPos = pos;
		
		//continue from current position and find the second " "
		if(pos != string::npos)
		{
			cout << "found again!" << endl;
			cout << pos << endl;
			command[1] = input.substr(currPos+1, pos);
			cout << "second string : " << command[1] << endl;
		}
	}
	else
		cout << "string not found" << endl;

	return 0;
}

The problem is that pos2 is finding the same space character as pos. Essentially you are doing this:

pos  = string( "Hello, world!" ).find( " " );
pos2 = string( "Hello, world!" ).find( " " );

The same space is found each time.

The find() function takes a second parameter which lets you specify where in the string you want to start looking. So:

// find all spaces
pos = -1;
cout << "Finding spaces in \"" << s << "\"\n";
do {
  pos = s.find( " ", pos+1 );
  if (pos != string::npos) cout << pos << '\n';
  }
while (pos != string::npos);

Each time through the loop we start looking after the last space found.

Hope this helps.

[EDIT] fixed my code. Forgot that string::npos == -1.

Thank you very much. Your code is very helpful for me. Now I can get the each string from a sentence olredi...^^ (so happy...)

This article has been dead for over six months. Start a new discussion instead.