Searching Strings

I need to extract what's between the first set of -'s ("my name is") and after the last - ("joe"). Is there a simple way of doing this?

1
2
3
4
5
6
7
8
9
10
11
12
13
int main() {
	string str = "hello - my name is - joe";
	string str2, str3;
	size_t pos;

	pos = str.find(" - ");
	cout << pos << endl;	// Returns 5

	pos = str.find(" - ");
	cout << pos << endl;	// Also returns 5

	return 0;
}
So I guess I could simplify my question to this:

if you have a STRING variable that contains the following:

<text> - <text> - <text>

How do I extract the three different pieces of text?
You have a delimiter that is '-'. So you can extract all charcaters delimited by '-'.
I read: http://www.cplusplus.com/reference/clibrary/cstring/strtok/

However it seems to work with character arrays, not a string object. Which is why I capitalized and bolded the word "string".

So would it still work on a string? If so HOW? lol :P

Also I will eventually need to compare the extracted data (for example "joe" with another string. Sooo it would be nice if the extracted data was a string, but if it's a char array, then how do I compare a char array with a string.

Thanks
Can someone please help with this...
I would use std::istringstream for this task. For example


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <sstream>
#include <string>

int main()
{
	std::string s = "hello - my name is - joe";

	std::istringstream is( s );

	while ( is )
	{
		std::string t;
		std::getline( is, t, '-' );
		std::cout << t << std::endl;
	}
}


The program output is

hello
my name is
joe

You can also use a string algorithm in particular find. For example

std::string::size_type pos = s.find( '-' );

Last edited on
Topic archived. No new replies allowed.