0% found this document useful (0 votes)
21 views

String in C

Uploaded by

Lena Devaraj
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

String in C

Uploaded by

Lena Devaraj
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

CHAPTER 8: Strings

What is a String?

 String is nothing but a collection of characters in a linear sequence. 'C'


always treats a string a single data even though it contains whitespaces. A
single character is defined using single quote representation. A string is
represented using double quote marks.

Example: "Welcome to the world of programming!"

 'C' provides standard library <string.h> that contains many functions


which can be used to perform complicated string operations easily.

Declaring and initializing a String Variables

 A string is a simple array with char as a data type. 'C' language does not
directly support string as a data type. Hence, to display a string in 'C', you
need to make use of a character array.
 The general syntax for declaring a variable as a string is as follows,

char string_variable_name [array_size];

 The classic string declaration can be done as follow:

char string_name[string_length] = "string";

 The size of an array must be defined while declaring a string variable


because it used to calculate how many characters are going to be stored
inside the string variable. Some valid examples of string declaration are as
follows,

char first_name[15];//declaration of string variable


char last_name[15];

 The above example represents string variables with an array size of 15.
This means that the given character array is capable of holding 15
characters at most. The indexing of array begins from 0 hence it will store
characters from a 0-14 position. The C compiler automatically adds a
NULL character '\0' to the character array created.
 Let's study the initialization of a string variable. Following example
demonstrates the initialization of a string variable,

char first_name[15] = "ANTHONY";


char first_name[15] = {'A','N','T','H','O','N','Y','\0'}; // NULL character '\0'
char string1 [6] = "hello";
/* string size = 'h'+'e'+'l'+'l'+'o'+"NULL" = 6 */
char string2 [ ] = "world";
/* string size = 'w'+'o'+'r'+'l'+'d'+"NULL" = 6 */
char string3[6] = {'h', 'e', 'l', 'l', 'o', '\0'} ; /*Declaration as set of characters ,Size 6*/

 In string3, the NULL character must be added explicitly, and the


characters are enclosed in single quotation marks.
 'C' also allow us to initialize a string variable without defining the size of
the character array. It can be done in the following way,

char first_name[ ] = "NATHAN";

 The name of a string acts as a pointer because it is basically an array.

String Input: Read a String from Terminal

 When writing interactive programs which ask the user for input, C
provides the scanf(), gets(), and fgets() functions to find a line of text
entered from the user.
scanf() function:

 When we use scanf() to read, we use the "%s" format specifier without
using the "&" to access the variable address because an array name acts
as a pointer. For example:

#include <stdio.h>
int main()
{
char name[10];
int age;
printf("Enter your first name and age: \n");
scanf("%s %d", name, &age);
printf("You entered: %s %d",name,age);
}

Output:

Enter your first name and age:


John_Smith 48

 The problem with the scanf function is that it never reads an entire string.
It will halt the reading process as soon as whitespace, form feed, vertical
tab, newline or a carriage return occurs. Suppose we give input as
"Guru99 Tutorials" then the scanf function will never read an entire string
as a whitespace character occurs between the two names. The scanf
function will only read Guru99.

gets() function:

 In order to read a string contains spaces, we use the gets() function. Gets
ignores the whitespaces. It stops reading when a newline is reached (the
Enter key is pressed).For example:

#include <stdio.h>
int main()
{
char filename[25];
printf("Enter your full name: ");
gets(full_name);
printf("My full name is %s ",full_name);
return 0;
}

Output:

Enter your full name: Dennis Ritchie


My full name is Dennis Ritchie

fgets() function:

 Another safer alternative to gets() is fgets() function which reads a


specified number of characters. For example:

#include <stdio.h>
int main()
{
char name[10];
printf("Enter your name plz: ");
fgets(name, 10, stdin);
printf("My name is %s ",name);
return 0;
}

Output:

Enter your name plz: Carlos


My name is Carlos

 The fgets() arguments are :

 the string name,


 the number of characters to read,
 stdin means to read from the standard input which is the
keyboard.

String Output: Print/Display a String to Screen


 C provides the printf(), puts(), and fputs() functions to displaying a
string on an output device.
printf() function:
 The standard printf function is used for printing or displaying a string on
an output device. The format specifier used is %s

Example,

printf("%s", name);

 String output is done with the fputs(), puts() and printf() functions.

fputs() function:

 The fputs() needs the name of the string and a pointer to where you want
to display the text. We use stdout which refers to the standard output in
order to print to the screen. For example:

#include <stdio.h>
int main()
{
char town[40];
printf("Enter your town: ");
gets(town);
fputs(town, stdout);
return 0;
}

Output:

Enter your town: New York


New York

puts() function

 The puts function prints the string on an output device and moves the
cursor back to the first position. A puts function can be used in the
following way,
#include <stdio.h>
int main()
{
char name[15];
gets(name); //reads a string
puts(name); //displays a string
return 0;
}

 The syntax of this function is comparatively simple than other functions.

String Handling Functions (The string library)

 The standard 'C' library provides various functions to manipulate the


strings within a program. These functions are also called as string
handlers. All these handlers are present inside <string.h> header file.

Function Purpose

strlen() This function is used for finding a length of


a string. It returns how many characters
are present in a string excluding the NULL
character.

strcat(str1, str2) This function is used for combining two


strings together to form a single string. It
Appends or concatenates str2 to the end of
str1 and returns a pointer to str1.

strcmp(str1, str2) This function is used to compare two


strings with each other. It returns 0 if str1
is equal to str2, less than 0 if str1 < str2,
and greater than 0 if str1 > str2.

 Lets consider the program below which demonstrates string library


functions:

#include <stdio.h>
#include <string.h>
int main ()
{
//string initialization
char string1[15]="Hello";
char string2[15]=" World!";
char string3[15];
int val;

//string comparison
val= strcmp(string1,string2);
if(val==0)
{
printf("Strings are equal\n");
}
else
{
printf("Strings are not equal\n");
}

//string concatenation
printf("Concatenated:%s",strcat(string1,string2));

//string length
printf("\nLengthstring1 :%d",strlen(string1));
printf("\nLengthstring2: %d",strlen(string2));

//string copy
printf("\nCopied:%s\n",strcpy(string3,string1));
//string1 is copied into string3

return 0;
}

Output:

Strings are not equal


Concatenated string:Hello World!
Length of first string:12
Length of second string:7
Copied string is:Hello World!

 Other important library functions are:

 strncmp(str1, str2, n) :it returns 0 if the first n characters of str1


is equal to the first n characters of str2, less than 0 if str1 < str2, and
greater than 0 if str1 > str2.
 strncpy(str1, str2, n): This function is used to copy a string from
another string. Copies the first n characters of str2 to str1
 strchr(str1, c): it returns a pointer to the first occurrence of char c
in str1, or NULL if character not found.
 strrchr(str1, c): it searches str1 in reverse and returns a pointer to
the position of char c in str1, or NULL if character not found.
 strstr(str1, str2): it returns a pointer to the first occurrence of str2
in str1, or NULL if str2 not found.
 strncat(str1, str2, n): Appends (concatenates) first n characters of
str2 to the end of str1 and returns a pointer to str1.
 strlwr() :to convert string to lower case
 strupr() :to convert string to upper case
 strrev() : to reverse string

Review Questions:

1. Define Array.
2. What do you meant by one dimensional array?
3. How to declare an array in C Program?
4. How to access the array elements?
5. Explain the initialization of two dimensional arrays.
6. Discuss multi dimensional array with example.
7. Write a C program to add two matrices.
8. Define static array.
9. What are the possible ways available in C to create dynamic arrays?
10. What are the functions we need to dynamic memory allocation?
11. State the difference of static and dynamic array.
12. What is String?
13. How to bring the string variable in C program?
14. How can you read a string from terminal?
15. What can we do to display a string on screen?
16. Explain various string handling functions with appropriate C program.

You might also like