Thread: How do you split a string of multiple words into single words

  1. #1
    Registered User
    Join Date
    Sep 2010
    Posts
    3

    How do you split a string of multiple words into single words

    I have a string variable that holds the full name of someone (ex. string fullName = "John Smith", how do I split that string and put the first and last name into separate string variables? I know to search for the space is a good way to start I'm just not sure how to go about doing this.

  2. #2
    Registered User
    Join Date
    Sep 2010
    Posts
    3
    (ex. string fullName = "John Smith"; )***

  3. #3
    Registered User
    Join Date
    Oct 2006
    Posts
    3,445
    I would put the string into an std::stringstream and use std::getline to extract words by specifying the delimiter as a space.

  4. #4
    Registered User
    Join Date
    Sep 2010
    Posts
    4
    I know this is probably overkill but I wrote a little utility code a couple years ago that splits up an input string into a series of tokens (output as a vector of strings). It might be helpful to you:

    Code:
    #include <string>
    #include <vector>
    
    /**
    * Splits a string up into a series of tokens (output as a string vector).
    *
    * @param	sourceStr	The string to split up.
    *
    * @param	delimiter	What to delimit the source string by.
    *
    * @param	ignoreEmpty    Whether or not to ignore empty tokens. 
    *                               (usually created by 2 or more immediately
    *                               adjacent delimiters)
    *
    * @return	A string vector containing a series of ordered tokens.
    */
    std::vector<std::string> split(const std::string &sourceStr, 
                                   const std::string &delimiter, 
                                   bool ignoreEmpty)
    {
    	std::vector<std::string> resultVector;
    
    	size_t idxA = 0;
    	size_t idxB = sourceStr.find(delimiter);
    	std::string tempStr;
    	bool done = false;
    
    	while(!done)
    	{
    		if(idxB != std::string::npos)
    		{
    			tempStr = sourceStr.substr(idxA, idxB-idxA);
    			idxA = idxB + delimiter.length();
    			idxB = sourceStr.find(delimiter, idxA);
    		}
    		else
    		{
    			tempStr = sourceStr.substr(idxA);
    			done = true;
    		}
    
    		if(!(ignoreEmpty && tempStr.empty()))
    			resultVector.push_back(tempStr);
    	}
    
    	return resultVector;
    }

  5. #5
    Unregistered User Yarin's Avatar
    Join Date
    Jul 2007
    Posts
    2,158
    Quote Originally Posted by mborba22 View Post
    I know to search for the space is a good way to start I'm just not sure how to go about doing this.
    Use string::iterator for this. Here's an example usage.

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by Yarin
    Use string::iterator for this.
    That is certainly feasible, but as demonstrated by ajs15822, std::string's own find functions are index based, as is substr. Elkvis' suggestion is probably the easiest to implement.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  7. #7
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    There is also Boost's string algorithms, which among others, contain a split function. Handy stuff. Something all programmers would benefit from.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  8. #8
    Banal internet user
    Join Date
    Aug 2002
    Posts
    1,380
    it's already been said but use stringstreams:

    Code:
    #include <iostream>
    #include <string>
    #include <sstream>
    using namespace std;
    
    
    int main()
    {
        string Token, ToParse("one two three four five");
        istringstream StrStream(ToParse);
    
        while (StrStream)
        {
            getline(StrStream, Token, ' ');
            cout << Token << endl;
        }
    
    /*
        //Alternatively:
        while (StrStream >> Token)
        {
            cout << Token << endl;
        }
    */
    
        return 0;
    }
    Outputs:
    one
    two
    three
    four
    five





    Or you really could just do something like this:
    Code:
    #include <iostream>
    #include <string>
    #include <sstream>
    using namespace std;
    
    
    int main()
    {
        string FullName("John Smith");
        string FirstName, LastName;
        istringstream StrStream(FullName);
    
        StrStream >> FirstName;
        StrStream >> LastName;
    
        cout << FirstName << endl;
        cout << LastName << endl;
    
        return 0;
    }
    FirstName and LastName will always be valid strings regardless of what FullName is
    Last edited by BMJ; 10-01-2010 at 04:46 PM. Reason: added another example

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. String Class
    By BKurosawa in forum C++ Programming
    Replies: 117
    Last Post: 08-09-2007, 01:02 AM
  2. String
    By maxorator in forum C++ Programming
    Replies: 8
    Last Post: 10-30-2005, 12:36 AM
  3. Calculator + LinkedList
    By maro009 in forum C++ Programming
    Replies: 20
    Last Post: 05-17-2005, 12:56 PM
  4. Classes inheretance problem...
    By NANO in forum C++ Programming
    Replies: 12
    Last Post: 12-09-2002, 03:23 PM
  5. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM