Question:
c programming help 20char?
Zack
2012-02-22 22:23:18 UTC
right now my program counts characters and spaces

how do I only count characters?

#include
int main()
{
char string[60];
int count;

printf("Please enter a string--> ");
gets(string);

for(count = 0; string[count] != '\0'; count++) {
}

printf("Your string is %d characters long.\n", count);
}
Five answers:
NIVED N
2012-02-23 01:40:21 UTC
int ccount =0;

for(count = 0; string[count] != '\0'; count++) {

if(string[count]!=' ')

ccount++;

}

ccount is the number of characters without spaces
modulo_function
2012-02-22 22:37:24 UTC
The obvious thing to do is to test each char in the string and only increment a count when that char is not a space:



int ccnt = 0;

for( count = 0; string[count]!='\0'; count++ ) {

...if( string[count]!=' ' ) ccnt++;

}



Then print the value of ccnt rather than count.
?
2012-02-23 08:26:31 UTC
you can use the isspace() function declared in ctype.h





#include

#include

int main()

{

char string[60];

int count;

int nSpace=0;



printf("Please enter a string--> ");

gets(string);

for(count = 0; string[count] != '\0'; count++) {

if(! isspace(string[count]))

nSpace++;

}



printf("Your string is %d characters long.\n and the number of non white characters is %d\n", count,nSpace);

return 0;



}
Rog
2012-02-22 23:34:06 UTC
int ccnt = 0;

for( count = 0; string[count]!='\0'; count++ ) {

if( string[count]!=' ' ) ccnt++;

}



printf("Your string has %d characters .\n", count-ccnt);

printf("Your string has %d spaces.\n", ccnt);
Jag
2012-02-23 05:39:40 UTC
I assume that you want to count the number of characters only(not digits, alpha numeric, or blank characters)



#include

#include



int main()

{

char string[60];

int count, itr;



printf("Please enter a string--> ");

gets(string);



count = 0;



for( itr=0; string[itr] != '\0'; itr++)

{

if( isalpha(string[itr] || isalnum(string[itr]) || isblank(string[itr]) || isdigit(string[i]) )

continue;

else

count++;

}



printf("Nos of characters present is [%d]\n", count);

}



For more information refer Standard C Library Functions ,and the include file : #include , since it includes many macros along with the above used macros:



ctype, isalpha, isalnum, isascii, isblank, iscntrl, isdigit,islower, isprint, isspace, isupper, ispunct, isgraph, isxdi-git - character handling



#include



int isalpha(int c);

int isalnum(int c);

int isascii(int c);

int isblank(int c);

int iscntrl(int c);

int isdigit(int c);

int isgraph(int c);

int islower(int c);

int isprint(int c);

int ispunct(int c);

int isspace(int c);

int isupper(int c);

int isxdigit(int c);



These macros classify character-coded integer values. Each is a predicate returning non-zero for true, 0 for false. The behavior of these macros, except isascii(), is affected by the current locale (see setlocale(3C)).


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...