When copying a string, you stop when you get to the '\0'
(and then make sure to copy the '\0'
).
When copying an int array, you typically copy the entire array.
#include <string.h> /* Assumed for subsequent examples */ #include <ctype.h> /* Assumed for subsequent examples */ int count(char s[]) { int count=0, i; for (i=0; s[i] != '\0'; i++) if (isalnum(s[i])) count++; return count; }
int count(char s[]) { int count=0, i; for (i=0; s[i] != '\0'; i++) { switch (s[i]) { case 'a': case 'e': case 'i': case 'o': case 'u': case 'y': /* If you think 'y' is a vowel */ count++; } } return count; }
void despace(char s[]) { int out=0, in; for (in=0; s[in] != '\0'; in++) { if (s[in] != ' ') s[out++] = s[in]; } s[out] = '\0'; }
int count(char s[]) { int count=0, i; for (i=0; s[i] != '\0'; i++) { char c = s[i]; if (c=='.' || c=='!' || c=='?') { char c2 = s[i+1]; if (c2==' ' || c2=='\0') { count++; } } } return count; }
This is quite similar to #5. Where #5 counted the ends
of sentences (one of .!? followed by a space or '\0'
),
we would count the ends of words
(a non-space followed by a space or '\0'
),
strcmp( "april", "April" )In ASCII, 'a' comes after 'A'. Hence, "april" is greater than "April", so strcmp will return a number greater than zero. Do this command to read about ASCII:
man ascii
#include <ctype.h> ... char c = ...; char upper = toupper(c);
char name[] = "Cookie"; char name[] = {'C','o','o','k','i','e'}; char name[7]; strcpy(name, "Cookie");
strcat(a,b)
appends b
to the end
of a
.
strcpy(a,b)
copies b
to a
,
replacing a
's previous value.
filename[strlen(filename)-4] = '\0'; /* Why 4? Because .txt is four characters. */
char buf[80]; char c; int i,j,k; fgets(buf, sizeof(buf), stdin); sscanf(buf, "%c%d%d%d", &c, &i, &j, &k);
printf("size: %d\n", strlen(title));
Whatever code is processing the string will simply continue
until it finds a '\0'
, somewhere.
It'll either find one, or it will hit the end of your allocated
address space, and then your program will fail with a confusing
error message.
int value = atoi(score);
isdigit