Results 1 to 3 of 3

Thread: Count words of a string

  1. #1

    Thread Starter
    PowerPoster eranga262154's Avatar
    Join Date
    Jun 2006
    Posts
    2,201

    Count words of a string

    Hi all,

    I want to find the number of words in a string(actually it can be a paragraph either). I found the new line character as follows.

    Code:
    int numberOfWords = 1;
    	string st(pBuffer);
    
    	for(int i = 0;i <= st.length(); i++)
    	{
    		// Newline
    		if(pBuffer[i] == '\n')
    		{
    			numberOfWords ++;
    		}
    
    	}
    My question is, say I have put more than one new line character at the end or middle of the string. All of them also count as another word of a string. How can I avoid it.
    “victory breeds hatred, the defeated live in pain; happily the peaceful live giving up victory and defeat” - Gautama Buddha

  2. #2
    type Woss is new Grumpy; wossname's Avatar
    Join Date
    Aug 2002
    Location
    #!/bin/bash
    Posts
    5,682

    Re: Count words of a string

    Code:
    int numberOfWords = 1;
    string st(pBuffer);
    
    for(int i = 1;i <= st.length(); i++)
    {
    	// Newline
    	if((pBuffer[i] == '\n') && (pBuffer[i-1] != '\n'))
    	{
    		numberOfWords ++;
    	}
    }
    Something like that anyway, I haven't tried it.
    Last edited by wossname; Dec 17th, 2007 at 07:20 AM.
    I don't live here any more.

  3. #3

    Thread Starter
    PowerPoster eranga262154's Avatar
    Join Date
    Jun 2006
    Posts
    2,201

    Re: Count words of a string

    I've followed quite same way to do this. Here is my code.

    C++ Code:
    1. bool isLastCharBlank = true;
    2.     int iWordCount = 0;
    3.  
    4.     char * szTemp = szInputString;
    5.  
    6.     while(*szTemp)
    7.     {
    8.         // Whitespase, tab, newline and carriage return
    9.         if ((*szTemp == ' ') || (*szTemp == '\n') || (*szTemp == '\r'))
    10.         {
    11.             isLastCharBlank = true;
    12.         }
    13.  
    14.         else if (isLastCharBlank)
    15.         {
    16.             iWordCount++;
    17.             isLastCharBlank = false;
    18.         }
    19.         szTemp++;
    20.     }
    21.     cout << iWordCount;

    What you think of it.
    “victory breeds hatred, the defeated live in pain; happily the peaceful live giving up victory and defeat” - Gautama Buddha

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width