50 likes | 242 Views
STRING. popo. Strings. In C, strings are just an array of characters Terminated with ‘’ character Arrays for bounded-length strings Pointer for constant strings (or unknown length). char str1[15] = “Hello, world!<br>”; char *str2 = “Hello, world!<br>”;. C, …. H. e. l. l. o. ,. w.
E N D
STRING popo
Strings • In C, strings are just an array of characters • Terminated with ‘\0’ character • Arrays for bounded-length strings • Pointer for constant strings (or unknown length) char str1[15] = “Hello, world!\n”; char *str2 = “Hello, world!\n”; C, … H e l l o , w o r l d ! \n terminator C terminator: ’\0’ Pascal, Java, … length H e l l o , w o r l d ! \n • popo Arrays and Pointers
String length • Must calculate length: • Provided by standard C library: #include <string.h> can pass an array or pointer int strlen(char *str) { int len = 0; while (str[len] != ‘\0’) len++; return (len); } Check for terminator array access to pointer! What is the size of the array??? • popo Arrays and Pointers
Implementing Some of These void strcpy(char *s, char *t) { int i = 0; while((s[i] = t[i]) != ‘\0’) i++; } intstrcmp(char *s, char *t) { inti; for(i=0;s[i] = = t[i];i++) if(s[i] = = ‘\0’) return 0; return s[i] – t[i]; } intstrlen(char *s) { int n; for(n = 0; *s != ‘\0’; s++) n++; return n; } void strcpy(char *s, char *t) { while((*s = *t) != ‘\0’) { s++; t++; } } intstrcmp(char *s, char *t) { for( ; *s = = *t; s++, t++) if(*s = = ‘\0’) return 0; return *s - *t; } void strcpy(char *s, char *t) { while((*s++ = *t++) != ‘\0’); } • popo
STRING • Notice that these functions receive parameters of type char * instead of arrays. Why? Recall that C uses pass-by-copy, so what is copied from the calling function to the called function is a pointer to the string array. We could also implement these with parameters of type char s[ ] if we prefer, but using *s is closer to what is really happening. The parameter is a pointer into an array. • Now, for any of these functions to work, we must assume that the last character in any string is ‘\0’. This is automatically inserted for us if we input the array using scanf, or if we directly assign the array to a string when declared, as in • char string[ ] = “hello”; • However, the ‘\0’ is not inserted if we do this: • char notAString[ ] = {‘h’, ‘e’, ‘l’, ‘l’, ‘o’}; • Because, in this case, the variable is thought of as a true char array. • popo