Introduction
Strings in c are implemented as arrays of characters terminated by the NULL (10′) character. This session discusses the usage and manipulation of strings.
variables and constants
String variables are used to store a series of characters. Like any other variable, these variables must be declared before they are used. A typical string variable declaration is:
char str [10];
str is a character array variable that can hold a maximum of 10 characters. Consider that str is assigned a string constant,
“WELL DONE”
A string constant is a sequence of characters surrounded by double quotes. Every character in the string is stored as an array element. In memory, the string is stored as follows:
‘W’ | ‘E’ | ‘L’ | ‘L’ | ‘ ’ | ‘D’ | ‘O’ | ‘N’ | ‘E’ | ‘\0’ |
The ’10’ (null) character is automatically added in the internal representation so that the program can locate the end of the string. So, while declaring a string variable, allow one extra element space for the null terminator.
Pointers to strings
Strings can also be stored and accessed using character pointers. A character pointer to a string is declared as follows:
char *pstr = “WELCOME” ;
pstr is a pointer that is initialized to point to a string constant. The pointer may be modified to point elsewhere. However, the modification would cause the string to be inaccessible.
Strings
Strings 1/0 operations
String input/output (I/O) operations in C are carried out using function calls. These functions are part of the standard 1/0 library called stdio. h. A program that uses the string I/0 functions must have the following statement at the beginning:
#include ‹stdio.h>;
When the program containing this statement is compiled, the contents of the file stdio.h become a part of the program.
Simple Strings I/0 operations
The gets () function is the simplest method of accepting a string through standard input. Input characters are accepted till the Enter key is pressed. The gets () function replaces the terminating ‘\n’ new line character with the ’10’ character. The syntax is as follows:
gets (str) ;
where, str is a character array that has been declared.
Similarly, the puts () function is used to display a string on the standard output device. The newline character terminates the string output. The function syntax is:
puts (str) ;
where, str is a character array that has been declared and initialized. The following program accepts a name and displays a message.
Example
#include ‹ stdio.h>
void main ()
{
char name (20];
/* name is declared as a single dimensional character array*/
puts ("Enter your name:"): /* Displays a message */
gets (name); / Accepts the input */
puts ("Hi there:"):
puts (name); /* Displays the input */
}
If the name Lisa is entered,
Output
Enter your name:
Lisa
Hi there:
Lisa
Formatted string 1/0 operations
The scanf () and printf () functions can also be used to accept and display string values. These functions are used to accept and display mixed data types with a single statement. The syntax to accept a string is as follows:
scanf (“es”, str) ;
where %s is the format specifier that states that a string value is to be accepted. str is a character array that has been declared. Similarly, to display a string, the syntax is:
printf (“es”, str) ;
where the %s format specifier states that a string value is to be displayed and str is a character array that has been declared and initialized. The printf () function can also be used without the format specifier to display messages.
The earlier program can be modified to accept and display a name using scan () and
printf().
Strings
Strings Functions
C supports a wide range of string functions, which are found in the standard header file string .h. Few of the operations performed by these functions are:
- Concatenating strings
- Comparing strings
- Locating a character in a string
- Copying one string to another
- Calculating the length of a string
The ‘strat()’ function
The strcat () function is used to join two string values into one. The syntax of the function is:
strcat (strl, str2) ;
where, strl and str2 are two character arrays that have been declared and initialized. The value in sti2 is attached at the end of str1.
The following program accepts a first name and a last name. It concatenates the last name to the first name and displays the concatenated name.
Example
#include<stdio.h>
#include<string.h>
void main ()
{
char firstname [15] ;
char lastname [15];
printf ("Enter your first name:");
scanf ("%s" , firstname) ;
printf ("Enter your last name:");
scanf ("%S", lastname) :
strcat (firstname, lastname) :
/* Attaches the contents of lastname at the end of firstname */
printf("&s", firstname) ;
}
Output
Enter your first name: Carla
Enter your last name: Johnson
CarlaJohnson
The ‘strcmp()’ function
The equality (or inequality) of two numbers can be verified using relational operators. However, to compare strings, a function call has to be made. The function strcmp () compares two strings and returns an integer value based on the results of the comparison. The syntax of the function is:
stremp (strl, str2) ;
where, str1 and str2 are two character arrays that have been declared and initialized. The function returns a value:
- Less than zero if strl < str2
- Zero if str1 is same as str2
- Greater than zero if strl › str2
The following program compares one name with three other names and displays the results of the comparisons.
Example
#include <stdio.h>
#include<string.h>
void main ( )
{
char namel [15] - "Geena";
char name2[15] - "Dorothy";
char name3 [15] = "Shania";
char name4 [15] - "Geena";
int i:
i = strcmp (namel, name2) :
printf ("%s compared with is returned %d\n", namel, name2, i):
i-strcmp (namel, name3) ;
printf ("%s compared with is returned %d\n", namel, name, i);
i-strcmp (namel, name4) ;
printf("es compared with is returned ®a\n", namel, name, i):
}
Output
Geena compared with Dorothy returned 3
Geena compared with Shania returned -12
Geena compared with Geena returned o
The ‘strchr()’ function
The strchr () function determines the occurrence of a character in a string. The syntax of the function is:
strchr (str, chr) ;
where, str is a character array or string. chr is a character variable containing the value to be searched. The function returns a pointer to the value located in the string, or NULL if it is not present.
The following program determines whether the character ‘a occurs in two specified city names.
Example
#include<staio.h>
#include<string.h>
void main ()
{
char strl [15] = "New York";
char str2[15] - "Washington";
char chi = 'a', loc;
10c = strchr (str, chi) :
/* Checks for the occurrence of the character value held by chr */
/* in the first city name */
if (loc ! - NULL)
printf ("%c occurs in is\n", chr, strl);
else
printf("%c does not occur in &s\n", chr, strl) ;
loc = strchr (str2, chi) ;
/* Checks for the occurrence of the character in the second city name */
if (loc ! - NULL)
printf ("%e occurs in 8s\n", chr, str2);
else
printf ("%c does not occur in is\n", chr, str2):
Output
a does not occur in New York
a occurs in Washington
The ‘stropy()’ function
There are no operators in C for handling a string as a single unit. So, the assignment of one string value to another requires the use of the function strpy (). The syntax of the function is:
strpy (strl, str2) ;
where, str1 and str2 are character arrays that have been declared and initialized. The function copies the value in str2 onto str1 and returns str1.
The following program demonstrates the use of the strcpy () function. It changes the name of a hotel and displays the new name.
#include <stdio.h>
#include<string.h>
void main ()
{
char hotelnamel l15] - "Sea View";
char hotelname2[15] - "Sea Breeze";
printf ("The old name is es\n", hotelnamel) ;
strpy (hotelnamel, hotelname2) ;
/* Changes the hotel name */
printf ("The new name is ös\n", hotelnamel) ;
/* Displays the new name */
}
Output
The old name is Sea View
The new name is Sea Breeze
Passing Arrays to Functions
In C, when an array is passed as an argument to a function, only the address of the array is passed. The array name without the subscripts refers to the address of the array. The following code snippet passes the address of the array ary to the function fn_ary () :
void main ()
{
int ary[10];
...
fn_ary (ary) ;
...
}
If a function receives a single-dimensional array, the formal parameters can be declared in one of the following ways.
Fn_ary (int ary [10]) /* sized array */
{
:
}
or
fn arry (int ary []) /* unsized array */
{
:
}
Both the above declarations produce the same results. The first method employs the standard array declaration. In the second version, the array declaration simply specifies that an array of type int of some length is required.
The following program accepts numbers into an integer array. The array is then passed to a function sum_arr (). The function computes and returns the sum of the numbers in the array.
Passing Strings to Functions
Strings, or character arrays, can also be passed to functions. For example, the following program accepts the longest string in the array.
strings into a two-dimensional character array. Then, the array is passed to a function that determines
Example
#include < stdio.h›
void main ()
{
char lines [5] [201;
int ctr, longctr=0;
int longest (char lines_arr[](20]);
/* Function declaration */
for (ctr = 0; ctr < 5; ctr++) /* Accepts string values into the array */
{
printf ("\nEnter string 8d: ", ctr+1) ;
scanf ("8s", lines|ctrl) ;
}
longctr = longest (lines) :
/* Passes the array to the function */
printf ("InThe longest string is 8s", lines[longctr]) ;
}
int longest (char lines_arr[][20]) /* Function definition */
{
int 1=0, 1_ctr=0, prev_len, new_len;
prev_len = stren (lines arr[i]);
/* Determines the length of the first element */
for (2++;1<5:2++)
{
new len=strlen (lines arril);
/* Determines the length of the next element */
if(new len > prevlen)
1_ctr=ュ:
/* Stores the subscript of the longer string */ prev_len - new len;
}
return 1 ctr;
/* Returns the subscript of the longest string */
}
Output
Enter string 1: The Enter string 2: Sigma
Enter string 3: Protocol
Enter string 4: Robert
Enter string 5: Ludlum
The longest string is Protocol
Summary
- Strings in C are implemented as arrays of characters terminated by the NULL (10″)
- String variables are used to store a series of characters.
- A string constant is a sequence of characters surrounded by double quotes.
- Strings can be stored and accessed using character pointers.
- String 1/0 operations in C are carried out using functions that are part of the standard I/O library called stdio.h.
- The gets) and puts) functions are the simplest method of accepting and displaying strings respectively.
- The scanf() and printf) functions can be used to accept and display strings along with other data types.
- C supports a wide range of string functions, which are found in the standard header file string.h.
- The strat) function is used to join two string values into one.
- The function strcmp() compares two strings and returns an integer value based on the results of the comparison.
- The strchr) function determines the occurrence of a character in a string.
- The strepy() function copies the contents of one string onto another.
- The strlen() function returns the length of a string.
- In C, when an array is passed as an argument to a function, only the address of the array is passed.
- The array name without the subscripts refers to the address of the array.
Leave a Reply