Lecture09 Strings
Lecture09 Strings
Lecture09 Strings
LECTURE 09
CCC101 - Introduction to Programming 1
Jennifer Joyce M. Montemayor
Example
‣ using the null terminating character as marker allows the string’s length
to vary from 0 to one less than the array’s declared size
Example
printf() function
scanf() function
‣ when provided with a string argument, we must remember that array as arguments
are always passed to functions by sending the address of the initial array element.
Therefore we don’t apply the address-of operator to a string argument passed to any
function.
‣ starting with the rst nonwhitespace character, it copies the characters into
successive memory cells of it’s character array argument
‣ when it comes across a whitespace character, scanning stops, and scanf places the
null character at the end of the string
char friend[30];
scanf(“%s”, friend);
Example
#define NUM_PEOPLE 30
#define NAME_LEN 25
#include<string.h>
‣ copies the string that is it’s second argument into its rst argument
strncpy Function
These functions makes up for not being able to use the ‘=’ operator / assignment
operator to set the value of a string variable.
char one_str[20];
one_str = “Test string”; //wrong!
strcpy(one_str, “Test string”); //correct!
strncpy(dest,source, dest_len-1);
dest[dest_len-1] = ‘\0’;
11 Jennifer Joyce M. Montemayor / CCC101 / Lecture 09
fi
fi
STRING OPERATIONS
Copy Strings
Example 1
strncpy(a,&pres[7],4);
a[4] = ‘\0’;
strcpy(b,&pres[12]);
strncpy(c,pres,5);
c[5] = ‘\0’;
strncpy(a,&pres[7],4); //“John”
a[4] = ‘\0’;
strcpy(b,&pres[12]); //“Quincy”
strncpy(c,pres,5); //“Adams”
c[5] = ‘\0’;
Example
8 16
Jupiter Symphony
#define STRSIZ 15
printf("%s",strcat(f1, last));
printf("%s",strcat(f2, last));
#define STRSIZ 15
printf("%s",strcat(f1, last));
//invalid! f2 overflow!
printf("%s",strcat(f2, last));
// make room for the null terminating character!
printf("%s",strncat(f2, last, 3));
#define STRSIZ 15
printf("%s",strcat(f1, last));
Example
Example
int a, b, c;
a = strcmp(word1, word2);
c = strcmp(&word1[3], &word2[2]);
int a, b, c;
a = strcmp(word1, word2);
c = strcmp(&word1[3], &word2[2]);
a = -4; b = 0; c = 3;
27 Jennifer Joyce M. Montemayor / CCC101 / Lecture 09
fi
STRING OPERATIONS
Convert Strings to Uppercase and Lowercase
strlwr Function
strupr Function
int main() {
s3[5];
s2[1] = '\0';
}
fi