0

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

4
Contributors
18
Replies
28
Views
9 Years
Discussion Span
Last Post by eranga262154
0

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

0

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.

0

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

0

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

0

Correction to WolfPack post....

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

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

0

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

0

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

0

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

0

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.

0

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.