Trying to extract words

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Nen013
    New Member
    • Oct 2009
    • 1

    Trying to extract words

    So I'm trying to create a function that will extract a word from a string. I'm trying to do this without creating an array. So far I have this:

    string s = "Hello World";
    string t;
    for (size_t k = 0; k!=s.size(); k++)
    {if (isalpha(s[k]))
    t+=s[k];
    else
    ???;
    }
    cout << t << endl;

    Basically I'm wondering what to put in the ??? part. Because I want the program to stop taking in characters once it hits a non-letter character.

    Or is there any easy method of doing this?
  • whodgson
    Contributor
    • Jan 2007
    • 542

    #2
    What is s[k]....an array?
    Also what is size_t defined as ....an int?
    Which word do you wish to 'extract' ......the first word, the fourth word or some specific word like "?????" ?
    Are you intending to print the string, pick the word to extract then extract it? or are you just intending to nominate a word like "thermocoup le" and if it happens to be in the string censor it?
    Are vectors also banned?..... because you can delete an element from a vector.
    Sorry this is so unhelpful

    Comment

    • sumeshnb
      New Member
      • Feb 2009
      • 13

      #3
      you can put a break statement in place of ????, so that the program will break from the for loop .

      string s = "Hello World";
      string t;
      for (size_t k = 0; k!=s.size(); k++)
      {if (isalpha(s[k]))
      t+=s[k];
      else
      break;
      }
      cout << t << endl;

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        You need to write down your algorithm first. Then code it.

        Maybe:

        1) remove whitespace
        2) move characters to your word until a) you hit whitespace or b) you run out of input.
        3) repeat from 1 ofer the next word.

        Comment

        Working...