Lecture09 Strings

Download as pdf or txt
Download as pdf or txt
You are on page 1of 29

Strings

LECTURE 09
CCC101 - Introduction to Programming 1
Jennifer Joyce M. Montemayor

Department of Computer Science


College of Computer Studies
MSU - Iligan Institute of Technology
Objectives
‣ to understand how a string constant is stored in an array
of characters

‣ to learn about the placeholder %s and how it is used in


printf and scanf operations

‣ to learn some of the operations that can be performed on


strings such as copying strings, extracting substrings,
and joining strings using functions from the library string

‣ to understand how C compares two strings to determine


their relative order

2 Jennifer Joyce M. Montemayor / CCC101 / Lecture 09


String
‣ is a collection or grouping of characters

‣ important because many computer applications are


concerned with the manipulation of textual data rather
than numerical data

‣ always enclosed in double quotes

Example

“hello world” “Welcome” “Fun Programming”

3 Jennifer Joyce M. Montemayor / CCC101 / Lecture 09


String
Initializing a String variable

‣ C permits the initialization of a string variable using a string constant

char str[20] = “Initial value”;

‣ strings are stored in an array of characters along with the null


terminating character ‘\0’ that marks the end of the string

‣ 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

‣ whatever is stored in the memory cells following the null terminating


character are ignored

4 Jennifer Joyce M. Montemayor / CCC101 / Lecture 09


String
Initializing a String variable

Example

The longest string the variable str can represent is


19 + the null terminating character.

5 Jennifer Joyce M. Montemayor / CCC101 / Lecture 09


Strings as Input and Output
‣ both printf() and scanf() can handle string arguments as long as
the placeholder %s is used in the format string

printf() function

‣ depends on nding a null terminating character that marks the end of


string.

char topic[30] = {“String and String Operations”};


printf(“%s”, topic);

‣ If passed a character array that contains no terminating character then it


would rst interpret the contents of the character array and display
them. Then it would continue to display as characters the content of the
memory location following the array argument until it encounters a null
terminating character or it attempts to access a memory location that
was not assigned to the program, causing a run-time error.
6 Jennifer Joyce M. Montemayor / CCC101 / Lecture 09
fi
fi
Strings as Input and Output
‣ both printf() and scanf() can handle string arguments as long as the
placeholder %s is used in the format string

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.

‣ skips leading whitespace characters

‣ 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);

7 Jennifer Joyce M. Montemayor / CCC101 / Lecture 09


fi
Arrays of Strings
‣ remember that one string is an array of characters, so an
array of strings is a two-dimensional array of characters in
which each row is one string

Example

#define NUM_PEOPLE 30
#define NAME_LEN 25

char names [NUM_PEOPLE][NAME_LEN];

char month[12][10] = {"January", "February",


"March", "April","May", "June", "July",
"August","September", "October", “November”,
"December"};
8 Jennifer Joyce M. Montemayor / CCC101 / Lecture 09
String Operations
‣ Strings or character arrays are a special type of array
that uses a ‘\0’ character at the end. As such it has its
own header library called string.h that contains built-
in functions for performing operations on these speci c
array types.

‣ You must include the string header le in your programs


to be able to use th built-in functions:

#include<string.h>

9 Jennifer Joyce M. Montemayor / CCC101 / Lecture 09


fi
fi
STRING OPERATIONS
Copy Strings
strcpy Function

‣ copies the string that is it’s second argument into its rst argument

strncpy Function

‣ takes an additional argument n to specify the number of characters to copy. If the


string to be copied is shorter than n characters, the remaining characters stored are
null.

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!

10 Jennifer Joyce M. Montemayor / CCC101 / Lecture 09


fi
STRING OPERATIONS
Copy Strings
However, when the source string is longer than n characters, only the rst n
characters are copied.

strncpy(one_str, “A very long test string”, 20);

Notice that the stored string above is invalid. There is no terminating


character ‘\0’

To avoid performing invalid operations, one can assign as much as will t of


a source string (source) to a destination string (dest) of length
(dest_len) less than 1 to make room for the terminating character.

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

char result[10], s1[15] = “Jan. 30, 1996”;


strncpy(result, s1,9);
result[9] = ‘\0’;

12 Jennifer Joyce M. Montemayor / CCC101 / Lecture 09


STRING OPERATIONS
Copy Strings
Example 2

char a[20], b[20], c[20];


char pres[20] = “Adams, John Quincy”;

strncpy(a,&pres[7],4);
a[4] = ‘\0’;

strcpy(b,&pres[12]);

strncpy(c,pres,5);
c[5] = ‘\0’;

13 Jennifer Joyce M. Montemayor / CCC101 / Lecture 09


STRING OPERATIONS
Copy Strings
Example 2

char a[20], b[20], c[20];


char pres[20] = “Adams, John Quincy”;

strncpy(a,&pres[7],4); //“John”
a[4] = ‘\0’;

strcpy(b,&pres[12]); //“Quincy”

strncpy(c,pres,5); //“Adams”
c[5] = ‘\0’;

14 Jennifer Joyce M. Montemayor / CCC101 / Lecture 09


STRING OPERATIONS
Copy Strings
Example 3

char socsec[12] = “123-456-789”;


char ssnshort[7], ssn1[4], ssn2[3], ssn3[5];

Write statements to accomplish the following:

1. store in ssnshort as much of socsec will t

2. store in ssn1 the rst three characters of socsec

3. store in ssn2 the middle two-digit portion of socsec

4. store in ssn3 the nal four digits of socsec

15 Jennifer Joyce M. Montemayor / CCC101 / Lecture 09


fi
fi
fi
STRING OPERATIONS
Length of String
strlen Function

‣ returns an integer corresponding to the length of string


less the null terminating character

Example

char firstname[30] = “Bob”;


int length = strlen(firstname);

This would set length to 3.

16 Jennifer Joyce M. Montemayor / CCC101 / Lecture 09


STRING OPERATIONS
Concatenation of Strings
strcat and strncat Function

‣ used to append one string to another

‣ join two strings to form a longer string

‣ modify rst string argument by adding all or part of their


second string argument at the end of the rst argument

‣ returns a char * which is the result of appending one


string to another

17 Jennifer Joyce M. Montemayor / CCC101 / Lecture 09


fi
fi
STRING OPERATIONS
Concatenation of Strings
Example 1

What will be the output of the code below?

char s1[20] = “Jupiter ”;


char s2[20] = “Symphony”;
printf(“%d %d\n”, strlen(s1), strlen(strcat(s1,s2)));
printf(“%s\n”, s1);

18 Jennifer Joyce M. Montemayor / CCC101 / Lecture 09


STRING OPERATIONS
Concatenation of Strings
Example 1

What will be the output of the code below?

char s1[20] = “Jupiter ”;


char s2[20] = “Symphony”;
printf(“%d %d\n”, strlen(s1), strlen(strcat(s1,s2)));
printf(“%s\n”, s1);

8 16

Jupiter Symphony

19 Jennifer Joyce M. Montemayor / CCC101 / Lecture 09


STRING OPERATIONS
Concatenation of Strings
Example 2

What will be the output of the code below?

#define STRSIZ 15

char f1[STRSIZ] = “John ”,


f2[STRSIZ] = “Jacqueline ”,
last[STRSIZ] = “Kennedy”;

printf("%s",strcat(f1, last));

printf("%s",strcat(f2, last));

printf("%s",strncat(f2, last, 3));

20 Jennifer Joyce M. Montemayor / CCC101 / Lecture 09


STRING OPERATIONS
Concatenation of Strings
Example 2

What will be the output of the code below?

#define STRSIZ 15

char f1[STRSIZ] = “John ”,


f2[STRSIZ] = “Jacqueline ”,
last[STRSIZ] = “Kennedy”;

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));

21 Jennifer Joyce M. Montemayor / CCC101 / Lecture 09


STRING OPERATIONS
Concatenation of Strings
Example 2

What will be the output of the code below?

#define STRSIZ 15

char f1[STRSIZ] = “John ”,


f2[STRSIZ] = “Jacqueline ”,
last[STRSIZ] = “Kennedy”;

printf("%s",strcat(f1, last));

printf("%s",strncat(f2, last, 3));

John KennedyJacqueline Ken

22 Jennifer Joyce M. Montemayor / CCC101 / Lecture 09


STRING OPERATIONS
Comparison of Strings
strcmp and strncmp Function

‣ used to determine if two strings are the same

‣ returns an integer that represents the following


relationships,

string1 < string2 negative integer

string1 == string1 zero

string1 > string2 positive integer

Note: Review ASCII Table


23 Jennifer Joyce M. Montemayor / CCC101 / Lecture 09
STRING OPERATIONS
Comparison of Strings
strcmp and strncmp Function

1. if the rst n characters of string1 and string2 match and


string1[n],string2[n] are the rst nonmatching
corresponding characters, string1 is less than string2 if
string1[n] < string2[n]

Example

char string1[] = “thrill”;


char string2[] = “throw”;

First 3 letters match.


string1[3] < string2[3]
‘i’ < ‘o’
24 Jennifer Joyce M. Montemayor / CCC101 / Lecture 09
fi
fi
STRING OPERATIONS
Comparison of Strings
strcmp and strncmp Function

2. if string1 is shorter than string2 and all characters


of string1 match the corresponding characters of
string2, string1 is less than string2

Example

char string1[] = “joy”;


char string2[] = “joyous”;

25 Jennifer Joyce M. Montemayor / CCC101 / Lecture 09


STRING OPERATIONS
Comparison of Strings
Example

What will be the nal values of a, b and c?

char word1[25] = "computer";


char word2[25] = "computing";

int a, b, c;

a = strcmp(word1, word2);

b = strncmp(word1, word2, 5);

c = strcmp(&word1[3], &word2[2]);

26 Jennifer Joyce M. Montemayor / CCC101 / Lecture 09


fi
STRING OPERATIONS
Comparison of Strings
Example

What will be the nal values of a, b and c?

char word1[25] = "computer";


char word2[25] = "computing";

int a, b, c;

a = strcmp(word1, word2);

b = strncmp(word1, word2, 5);

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

‣ takes a string as an argument and converts it to a


lowercase string

strupr Function

‣ takes a string as an argument and converts it to an


uppercase string

28 Jennifer Joyce M. Montemayor / CCC101 / Lecture 09


The output of the following program is “Programming in C
is a game.” Fill in the most appropriate set of instructions
to ll in for the numbered steps in the program.
#include<stdio.h>

int main() {

char s1[] = "Programming in C", s2[5],

s3[5];

1. strncpy (s2, _______,1);

s2[1] = '\0';

2. ________(s3, &s1[ __ ], __); s3[2] = '\0';

3. ________( ______, strcat (s3,"e"));

printf ("%s is a %s\n", s1, s2);

}
fi

You might also like