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

Strings

A string is defined as a sequence of characters (letters, digits, symbols, and control


characters) which is to be considered as a single data item. It is one of the most useful
and fundamental data structures in C due to the fact that it is the data structure closest
to real human language. Strings are used to store or keep track of names, addresses, key
words, and a host of words that can easily distinguish one information from another.

In C, a string can be implemented as an array of characters that is terminated by a


null character ‘\0’.

9.1 String Constants

Any word or words, including spaces, enclosed in quotation marks are


considered as strings.

Example. “Hello World!”


“$ 123,000.00”
“--+Hi+--\n”
“12345”

Strings can also be defined as constants.

Example. #define ERROR “Wrong input!”


#define MY_MESSAGE “Hi, hello!”
#define ASQ “Who are you?”

9.2 Declarations and Initialization of String Variables

As mentioned earlier, a string in C is implemented as an array of characters


(char). An example would be

char str[10];

In the example, str is a string variable that could contain 10 characters


from indices 0 to 9. A special characteristic of strings is that they are terminated
by the null character ‘\0’.

A string can also be initialized. An example of a typical string


initialization would be

char str[10] = “Hi ppl!”

In this example str would be represented in memory as:


0 1 2 3 4 5 6 7 8 9

'H' 'i' ' ' 'p' 'p' 'l' '!' '\0' ? ?

where ? indicates unused/garbage values.

141
Chapter 9

It is important to note that even spaces take up memory location. Note


also that the null character, which terminates the string, takes up one space in
memory. Thus, str could only accommodate a maximum of 9 characters. In
general, if a string is declared to be an array of n characters, it can only
accommodate a maximum of (n – 1) characters.

Question: What if an initialization is performed wherein the length of the


initial value exceeds the maximum allowable length of the string?

Answer: Result becomes unpredictable.

9.3 Input/Output Using Strings

9.3.1 The scanf() and gets() function

Strings may be input using the scanf() function using the “%s” format
specification. An example would be

scanf(“%s”, str);

Using scanf() on strings is different from using scanf() on other data


types. The & symbol is not used because a string is an array and an array passed
to a function is automatically passed by reference.

scanf() works by looking for the first non-space character entered, and
continues to read the input characters until it reads another space character.
When a space is reached, then a ‘\0’ is written. For example, the two strings
“ abc “ and “abc” used as inputs for the above scanf() statement are
equivalent.

Because of this nature of scanf(), care should be taken when using it


because it could possibly store characters whose number is more than the
capacity of a string variable.

Question: What if the spaces entered are to be stored in a string variable?

Answer: Use the gets() function instead of scanf().

The gets() function reads the input characters until a newline character
‘\n’ is met. The newline character is replaced by a null character inside the
string.

The syntax for this function is as follows:

Format:

gets(<string variable>);

142
Strings

Example.
gets(str);

Given the sample gets statement, the two input strings “ abc “ and
“abc” are not anymore equivalent.

9.3.2 The printf() and puts() function

Strings can be output using the printf() function with "%s” as the format
specification.

Example.

printf(“%s\n”, str);
printf(“%s”, “Hello!\n”);

The function puts() can also be used to output a string. The syntax is as
follows:

Format:

puts(<string>);

Example.
puts(str);
puts(“What is your name?”);

It is important to note that using puts() would automatically append a


newline character.

9.4 String Library (string.h) Functions

9.4.1 String Length

To get the length of the string, we use the strlen function of the string library.

The syntax is as follows:

Format:

<integer variable> = strlen(<string>);

strlen returns the length of <string>, excluding the null character.

143
Chapter 9

Example.

strlen(“ abc “); -------------------→ returns 5

char str[10] = “abc”;


strlen(str); -----------------------→ returns 3

9.4.2 String copy

Since strings are array of characters, they cannot be assigned using the
assignment statement (unless it is part of the declaration). To copy a string to
another, the strcpy function is used. The strcpy has the following format:

Format:

strcpy(<string variable>, <source string>)

strcpy copies <source string> to <string variable>. The source string


may be a string literal or it may also be a string identifier.

Example.

strcpy(str, “bye”); -------------------→ str will contain “bye”

char str2[10] = “see you”;


strcpy(str, str2); -------------------→ str will contain “see you”

9.4.3 String compare

Unlike integers, float, and characters, we cannot use the relational and equality
operators to compare strings. Each of the characters in the string should be
compared. The string library of C provides this capability of comparing each
character through the strcmp function.

The syntax for strcmp is as follows:

Format:

<integer variable> = strcmp(<string1>, <string2>)

strcmp compares <string1> and <string2> alphabetically. Note that small


and capital letters are not equal. The function strcmp returns a 0 if the two
strings are equal, a positive value if <string2> should come before <string1>,
and a negative value if <string1> should come before <string2>.

144
Strings

Example.
char str1[10] = “hello”;
char str2[10] = “hellO”;

strcmp(str1, str2) will return a positive value (in this case, 32) because
the ASCII value of ‘O’ (79) is less than the ASCII value of ‘o’ (111).

str1
0 1 2 3 4 5 6 7 8 9

'h' 'e' 'l' 'l' 'o' '\0' ? ? ? ?

0 1 2 3 4 5 6 7 8 9

'h' 'e' 'l' 'l' 'O' '\0' ? ? ? ?

str2

Common Programming Errors

1. It is an error to assign strings to string variables. Assigning a string to a variable using


the assignment statement may only be done if the assignment is part of the declaration.
Otherwise, the strcpy function of the string library should be used.

char strWord[5];
strWord = “Hi”;

2. It is an error to compare strings by using relational or equality operators. Note that


comparing strings of different lengths is valid. Also, comparing a shorter string with a
longer string does not automatically mean that the shorter string will always precede
the longer string.

char string5[6] = “Hello”;


char strData[11] = “Earthlings”;

if (string5 >= strData)


puts(string5);

3. It is wrong to use the a relational or equality operator within the call to strcmp. The
strcmp function accepts 2 string parameters.

if (strcmp(string5 >= strData))


puts(string5);

145
Chapter 9

4. In using puts and gets, there should be no conversion characters. The puts and gets
functions are strictly for strings. Thus, the following statements are wrong:

char string5[6];
gets(“%s”, string5);
puts(“%s”, string5);
gets(“%d”, string5);
puts(“%d”, string5);

5. There is no need to put the & sign in a gets or a scanf statement since a string is an
array of characters. Remember that when an array is passed as a parameter, it is the
address that is passed. Thus, it is wrong to have statements such as the following:

char string5[6];
gets(&string5);
scanf(“%s”, &string5);

Chapter Exercises

1. Show the screen output of the following program.

#include <stdio.h>
#include <string.h>

#define MESSAGE “News Bulletin”

typedef char str9[10];


typedef char str50[51];

main()
{
str9 strName1;
str9 strName2 = “jane do”;
str50 strMyName, strOtherPerson;
int nSize, nCompare;

strcpy(strName1, “John Doe”);


printf(“strName1 contains %s\n”, strName1);
puts(“strName2 contains “);
puts(strName2);

nSize = strlen(strName2);
printf(“Size of strName2 is %d\n”, nSize);

nCompare = strcmp(strName1, strName2);


if (!nCompare )
puts(“The strings are equal”);
else if ( nCompare < 0 )
puts(“strName1 should be before strName2”);
else puts(“strName1 should be after strName2”);

146
Strings

printf(“My name is : “);


/*input your whole name*/
gets(strMyName);

puts(“One of my seatmate’s name is : “);


/*input a seatmate’s whole name*/
scanf(“%s”, strOtherPerson);

printf(“\n%s\n” , MESSAGE);
printf(“Scientist %s shows %s ”, strOtherPerson,
strMyName);
puts(“as proof that alien life form exist.”);
}

2. Create a function that will continuously ask for a string input from the user until
the input string has at least 6 characters. Assume that the maximum string to be
given by the user is 10 characters.

3. Given an array of 100 names, create a function findSubstring that will copy all
names containing a substring equal to strKey. Use the following function
outline:

typedef char strName[51];


typedef strName arrNames[100];

void findSubstring( arrNames aNameList,


arrNames aWithSubString,
strName strKey )
{
/* write your code here */
}

147

You might also like