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

This is a discussion on How do you split a string of multiple words into single words within the C++ Programming forums, part of the General Programming Boards category; I have a string variable that holds the full name of someone (ex. string fullName = "John Smith" , how ...

  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
    2,545
    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
    1,678
    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.
    A class that doesn't overload all operators just isn't finished yet. -- SmugCeePlusPlusWeenie
    A year spent in artificial intelligence is enough to make one believe in God. -- Alan J. Perlis

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    22,166
    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.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  7. #7
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    22,918
    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
    BMJ
    BMJ is offline
    Banal internet user BMJ's Avatar
    Join Date
    Aug 2002
    Location
    Chicagoland
    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 05: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, 02:02 AM
  2. String
    By maxorator in forum C++ Programming
    Replies: 8
    Last Post: 10-30-2005, 01:36 AM
  3. Calculator + LinkedList
    By maro009 in forum C++ Programming
    Replies: 20
    Last Post: 05-17-2005, 01: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, 07:49 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21