Download presentation
Presentation is loading. Please wait.
Published byShinta Kurniawan Modified over 6 years ago
1
Strings String constants String variables Traverse strings
2
String_ an array of characters terminated with an extra null character, ‘\0’
string constant_ “Enter YES or No: “ char *q = “Enter YES or No: “; char *q; q = “Enter YES or No: “; illegal: q[5] = ‘x’; q E n t e r ... N o : \0
3
Don’t forget to supply the trailing null character
string variable_ char q[18] = {‘E’,’n’,’t’,’e’,’r’,’ ‘,’Y’,’E’,’S’, ‘ ‘,’o’,’r’,’ ‘,’N’,’o’,’:’,’ ‘,’\0’}; char q[18] = “Enter YES or No: “; illegal: char *q = “Enter YES or No: “; char qcopy[100]; qcopy = q; Don’t forget to supply the trailing null character when creating a string. We can’t simply assign one character string to another, just as we couldn’t assign arrays.
4
int getline(char line[], int max)
/* * Read a single input line into an array. */ #include <stdio.h> int getline(char line[], int max) { int c; int i = 0; while ((c = getchar()) != '\n') if (i < max) line[i++] = c; line[i] = '\0'; return (i); }
5
strcat(s1,s2) strcpy(s1,s2) s2 s1 s2 s1 E F \0 A B C D \0 E F \0 A B C
6
strcmp(s1,s2) return 0 if equal
strlen(s) return length, not counting null character strchr(s,c) return a pointer to the first occurrence of c in s, or NULL getline(line, MAXLEN); if (strcmp(line, "yes")==0 || strcmp(line, "YES")==0) … ;
7
len = getline(inpline, MAXLEN); strcpy(newname, blankptr + 1);
/* * Name conversion program */ char inpline[MAXLEN + 1]; int len; char newname[MAXLEN + 2]; char *blankptr; /* pointer to blank separator */ len = getline(inpline, MAXLEN); blankptr = strchr(inpline, ' '); strcpy(newname, blankptr + 1); strcat(newname, ", "); *blankptr = '\0'; strcat(newname, inpline); printf("%s\n", newname); Alex Quilici Quilici, Alex
8
blankptr inpline A l e x Q u i l i c i \0 newname Q u i l i c i \0 ...
9
char *strcpy(char d[], char s[])
{ int i; for (i = 0; (d[i] = s[i]) != '\0'; i++); return d; } int strcmp(char s[], char t[]) for (i = 0; s[i] == t[i] && s[i] != '\0'; i++); return s[i] - t[i]; int strlen(char s[]) for (i = 0; s[i] != '\0'; i++); return i;
10
char *strcpy(char *dptr, char *sptr)
{ char * startptr = dptr; for (; (*dptr = *sptr) != '\0'; dptr++, sptr++); return startptr; } int strcmp(char *sptr, char *tptr) for (; *sptr == *tptr && *sptr != '\0'; sptr++, tptr++); return *sptr - *tptr; int strlen(char *ptr) char *startptr = ptr; for (; *ptr != '\0'; ptr++); return ptr - startptr;
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.