|
-
Dec 17th, 2007, 05:44 AM
#1
Thread Starter
PowerPoster
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
-
Dec 17th, 2007, 07:16 AM
#2
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.
-
Dec 17th, 2007, 10:31 PM
#3
Thread Starter
PowerPoster
Re: Count words of a string
I've followed quite same way to do this. Here is my code.
C++ Code:
bool isLastCharBlank = true;
int iWordCount = 0;
char * szTemp = szInputString;
while(*szTemp)
{
// Whitespase, tab, newline and carriage return
if ((*szTemp == ' ') || (*szTemp == '\n') || (*szTemp == '\r'))
{
isLastCharBlank = true;
}
else if (isLastCharBlank)
{
iWordCount++;
isLastCharBlank = false;
}
szTemp++;
}
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|