Hi,

I want to count the number of characters of a string. Try to do it as follows.

int iSpace = 0;
	int iLength;

	string strTemp("This is a line                      of text");
	iLength = strTemp.length();

	cout << iLength << endl;

	for(int i = 0; i < iLength; i++)
	{
		if((strTemp.at(i) == ' ') || (strTemp.at(i) == '\t') || (strTemp.at(i) == '\0'))
		{
			iSpace ++;
		}
	}
	printf("\nNumber of characters %d", (iLength - iSpace));

Can you guys comments on my code, either this way is ok or bad attempt

Recommended Answers

All 18 Replies

yup...looks fine to me. How about modifies it for user inputs? See if it can manipulate with users' requirements

Dealing with the user inputs wont difficult. Anyway I'll check it. What I'm really worried about is the way I find the characters of the string.

Easy...Try to insert the characters into an array. That way, you can see what contains in it more clearly

Use of an array can be more works. What it the my code odd you can see. Please let me know.

Use isspace for a check like this.

for(int i = 0; i < iLength; i++)
{
         if(!isspace(strTemp.at(i)))
         {
                  iSpace++;
         }
}

I was gonna post it ;(

Correction to WolfPack post....

for(int i = 0; i < iLength; i++){
            if(isspace(strTemp.at(i)))
            {
                              iSpace ++;
            }
    }

Seems both codes are same. And how to handle tabs there.

if you meant by ignoring the white spaces, you can use a struct @ while(ws != '\t')

But seems isspace() ignored both white spaces and tab spaces. Right?

Thats it...Actually, isspace() returns either 0 or 1. In other words, it gives a false or true. Just like conditions

Yep, I got it. Seems it is much better that use of (... == ...) style. I'll try it now.

Still, in a certain conditions, isspace() would produce more dependent ways of producing outputs. Its your program after all ;p

Yep, seems it is more reliable than use of few number of if() conditions. Output also seems much better there. Thanks pal.

No sweat, dude. Glad to help

The isspace(int ch) function returns nonzero if ch is a whitespace character, including space, horizontal tab, vertical tab, formfeed, carriage return, or newline character; otherwise, zero is returned.

No sweat, dude. Glad to help

Yep, I learn a lot from those replays. Thanks again

The isspace(int ch) function returns nonzero if ch is a whitespace character, including space, horizontal tab, vertical tab, formfeed, carriage return, or newline character; otherwise, zero is returned.

Yep, I go through the MSDN and found the way it works. Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.