Computer Programming C: UNIT II: Arrays and Strings

String Operations

C Programming

In general a string is a sequence of characters treated as one unit. Virtually all strings treated as a variable length piece of data.

STRING OPERATIONS

 

1. Introduction

2. String Manipulation

3. Reading and Writing string

4. Character Operations

5. Strings standard functions

i. The strlen() function

ii. The strcpy() function

iii. The strcat() function

iv. The strcmp() function

v. The strrev() function

vi. The strchr() Function

vii. The strlwr() function

viii. The strupr() function

 

1. INTRODUCTION

In general a string is a sequence of characters treated as one unit. Virtually all strings treated as a variable length piece of data.


For example one of the most common of all strings is a name. Names. vary by nature, by length and it makes no difference. Given that we have the data that can vary in size, how we accommodate them in our programs.


The fixed length string can be stored easily as we know the length of the string.

Variable length strings can contain non‒data characters such as spaces and end of the line etc., so these can be accommodated as well in see,

Length controlled strings add a count that specifies the number of characters in the strings.

Another technique used to identify the end of the string is the delimiter.


 

2. STRING MANIPULATION

In 'C' language, the group of character, digits, and symbols enclosed within quotation marks are called as string otherwise strings are array of characters.

Null character ('\0') is used to mark the end of the string.

Example: char name[]={'B', 'A', 'B', 'U', '\0'};

Each character is stored in one byte of memory and successive characters of the string are stored in successive byte.

Memory map of string


The variables that can hold more than a single character, is precisely where the array of characters comes into picture.

Example:

char word[] = { 'C', '0', 'M', 'P', 'U', 'T', 'E', 'R' };

Remembering that in the nonappearance of an array size, the C compiler automatically computes the number of elements in the array based upon the number of characters initialised, this statement reserves space in memory for exactly eight characters, as shown below.


Character arrays are special. They have certain initialisation properties not shared with other array types because of their relationship with strings. Of course, character arrays can be initialised in the normal way using an initialiser list.

char letters] = {'a', 'b', 'c', 'd', 'e' };

But they may also be initialised using a string constant, as follows.

 char letters [] = "abcde";

The string initialisation automatically appends a \0 character, so the above array is of size 6, not 5. It is equivalent to writing,

 char letters[] = { 'a', 'b', 'c', 'd', 'e', '\0' };

Thus, writing

 char letters[5] = "abcde";   /* OK but bad style. */

An important property of string constants is that they are allocated memory; they have an address and may be referred to by a char * pointer. For constants of any other type, it is not possible to assign a pointer because these constants are not stored in memory and do not have an address.

However, it is perfectly valid for a character pointer to be assigned to a string constant.

char *str = "Hello World!\n";

This is because a string constant has static extent memory which is allocated for the array before the program begins execution, and exists until program termination and a string constant expression returns a pointer to the beginning of this array.

NOTE: A string constant is a constant array; the memory of the array is read‒only. The result of attempting to change the value of an element of a string constant is undefined.

Example: char *str = "This is a string constant";

 

3. READING AND WRITING STRING

The "%s' control string can be used in scanf() statement to read a from the terminal and the same may be used to write string to the terminal in printf() statement.

Example:

char name[10];

scanf("%s", name);

printf("%s", name);

There is no address (&) operator used in scanf() statement.

Example 1: Reading a line of text.

/* Program to reading a line of text */

#include <stdio.h>

main()

{

      char line[100], ch;

      int n=0;

      printf("Enter text press RETURN to end \n");

      do

      {

            ch=getchar();

            line(n) = ch;

            n++;

      } /* do..while */

      while (ch!= '\n');

      n=n‒1;

      line(n) = '\0';

      printf("%s", line);

} /* main */d

OUTPUT

Enter text press RETURN to end

C language is very easy to learn.

EXPLANATION: In the above program, the variable line[] is declared as character array type. A do‒while loop get the character from keyboard until the condition satisfied ch!='\n'. Then the variable n decrement by 1 and assigned line(n)='\0' then print

Example 2: Program to illustrate string function.

* Program to illustrate string function */

#include <stdio.h>

#include <conio.h>

void main()

{

char ch;

int cnt = 0;

char s1[6]= "Hello";

char s2[6]= { 'H', 'e', 'l', 'l', 'o'};

printf ("%s\n", s1);

printf("%s\n", s2);

while((ch=getchar() != '\0') && (cnt <6‒1))

        s1[cnt++] ch;

s1[cnt] = '\0';

getch();

} /* main */ d

OUTPUT

Hello

Hello

EXPLANATION: This program aims on the concept of the strings. Here the string is assigned to different arrays in different ways and the contents of these arrays can be printed using while loop.

'C' Language supports a wide range of string handling functions, that can be used to carry out various string manipulations.

 

4. CHARACTER OPERATIONS

Character variables and constants are frequently used in relational and arithmetic expressions. To properly use characters in such situations, it is necessary for you to understand how they are handled by the C compiler.

Whenever a character constant or variable is used in an expression in C, it is automatically converted to, and subsequently treated as, an integer value.

Example: c >= 'a' && c <= '7'

Could be used to determine if the character variable 'c' contained a lowercase letter. As mentioned there, such an expression could be used on systems that used an ASCII character representation because the lowercase letters are represented sequentially in ASCII, with no other characters in between.

The first part of the preceding expression, which compares the value of 'c' against the value of the character constant 'a', is actually comparing the value of 'c' against the internal representation of the character 'a'. In ASCII, the character 'a' has the value 97, the character 'b' has the value 98, and so on.

Therefore, the expression c> = 'a' is TRUE (nonzero) for any lowercase character contained in "c' because it has a value that is greater than or equal to 97.

However, because there are characters other than the lowercase letters whose ASCII values are greater than 97, the test must be bounded on the other end to ensure that the result of the expression is TRUE for lowercase characters only. For this reason, 'c' is compared against the character 'z', which, in ASCII, has the value 122. Because comparing the value of 'c' against the characters ‘a' and 'z' in the preceding expression actually compares 'c' to the numerical representations of 'a' and 'z'.

Example 1: Program to find the string is palindrome or not.

#include <stdio.h>

#include <string.h>

int main()

{

char a[100], b[100];

printf("Enter the string to check if it is a palindrome \n");

gets(a);

strcpy(b,a);

strrev(b);

if( strcmp(a,b) == 0.)

      printf(“Entered string is a palindrome. \n");

else

      printf("Entered string is not a palindrome. \n");

}

OUTPUT

Try with below palindrome words

Max exam

Malayalam

A Santa at Nasa

Ma is a madam, as I am

Madam, I'm Adam

EXPLANATION: First, copy the entered string into a new string, and then reverse the new string and compare it with original string. If both of them have the same sequence of characters i.e. they are identical, then the entered string is a palindrome otherwise not.

Example 2: To sort names (strings) in ascending order.

#include <stdio.h>

#include <string.h>

#include <conio.h>

void main()

{

int num,i,j, result, index;

char name[25][25]; /*declaring array of strings */

char temp[25];

printf("Number of names to be sorted in ascending order\n");

scanf("%d", &num);

printf("Enter %d names to be sorted\n", num);

for(i=0;i<num;i++)

         scanf("%s", name[i]);  /*input the names*/

for(i=0;i<num;i++)

{

         index=i;

         for(j=i+1;j<num;j++)

         {

                  result = strcmp(name[index], name[j]);

                  if(result > 0)

                           index=j;

         }

}

strcpy(temp, name[index]);

strcpy(name[index], name[i]);

strcpy(name[i], temp);

}

printf("\nNames Sorted in Ascending Order\n");

for(i=0;i<num;i++)

         printf("\t%s", name[i]);

}

OUTPUT

Number of names to be sorted in ascending order 4

Enter 4 Names to be sorted

Basker

Aravind

Damu

Chinni

Names sorted in Ascending order

Aravind

Baskar

Chinni

Damu

EXPLANATION: The main logic to sort numbers in ascending order remains same over here, however the only difference is that we have to use string functions to compare two strings and also for swapping two strings we have to use string functions.


5. STRINGS STANDARD FUNCTIONS

The 'C' compiler provides the following string handling functions.

Function: Purpose

strlen(): Used to find the length of the string.

strcpy(): Used to copy one string to another.

strcat(): Used to combine two strings.

strcmp(): Used to compare characters of two strings (difference between small and capital letters).

strlwr(): Used to convert strings into lower case.

strupr(): Used to convert strings into upper case.

strdup(): Used to duplicate a string.

strrev(): Used to reverse a string.

strncpy(): Used to copy first 'n' characters of one string into another.

strncmp(): Used to compare first 'n' characters of two strings.

strcmpi(): Used to compare two strings without regarding the case.

strnicmp(): Used to compare first 'n' characters of two strings without regarding the case.

stricmp():Compares two strings (Not difference between small and capital letters).

strchr():Determines first occurrence of a given character in a string.

strrchr():Determines last occurrence of a given character in a string.

strstr():Determines first occurrence of a given string in another string.

strncat():Appends source string to destination string upto specified length.

strnset():Sets specified number of characters of string with a given argument or symbol.

strspn():Finds up to what length two strings are identical.

strpbrk(): Searches the first occurrence of the character in a given string and then it displays the string starting from that character.

The commonly used string manipulation functions are as follows:

5.1. The strlen() function

This function is used to count and return the number of characters present in a string.

Syntax: var = strlen(string);

Description:

var - Is the integer variable, which accepts the length of the string.

String - Is the string constant or string variable, in which the length is going to be found. The counting ends with first null (\0)char.

Example: Program using strlen() function.

/* Program using strlen() function */

#include <stdio.h>

#include <conio.h>

main()

{

          char name[] = "MUNI";

          int len1,len2;

          len1 = strlen(name); /* To find the length of the string */

          len2 = strlen("VRB");

          printf("\n string length of %s is %d",name,len1);

          printf("\n_string length of %s is %d,", "VRB",len2);

}  /* main */

OUTPUT

String length of MUNI is 4

String length of VRB is 3

EXPLANATION: The above program refers to check the length of the string. Here the character type name[] holds the element 'Muni', it is passed to variable len1. The len2 variable holds the elements of 'VRB' 'strlen' function detect the length of string len1 and len2 and print the result as above mentioned.

Here, while calculating the length of the string by using the strlen() the '\0' null character is not taken into consideration.

5.2. The strcpy() function

This function is used to copy the contents of one string to another and it almost works like string assignment operator.

Syntax: strepy (string1, string2);

Description:

String1 is the destination string

String2 is the source string

The contents of string2 is assigned to the contents of string1. Where string2 may be character array variable or string constant.

Example:

char str[]="MUNI";

char str2[]= "LAK";

strcpy(str1, str2);

Where the contents of str2 are copied into the strl and the contents of strl is replaced with new one.

Example

char str1[10];

strcpy(str1, "LAK");

Here, the string constants are copied to the string variable strl.

Example: Program using strcpy() function

/* Program using strcpy() function */

#include <stdio.h>

main ()

{

          char source = "MUNI"; *Local definitions */

          char target[10];

          strcpy(target,source);   /* string copy */

          printf("\n Source string is %s", source);

          printf("\n Target string is %s", target);

} /* main */

OUTPUT

Source string is MUNI'

Target string is MUNI

EXPLANATION: In the program the character type variable source contain a string "MUNI". The variable target[] is declared as a character type. Here the strcpy() function copy the source string "MUNI" into target string. Now the variable target also contain the string "MUNI" and print the variable source and target.

5.3. The strcat() function

The strcat() function is used to concatenate or combine, two strings together and forms a new concatenated string.

Syntax: strcat(string1, string2);

Description: string1 and string2 are character type arrays or string constants.

When the above strcat() function is executed, string2 is combined with string1 and it removes the null character (\0) of string1 and places string2 from there.

Example:

            strcat("MUNI”, “LAK”)

Yields  MUNILAK

            char strl="MUNI”

            char str2="LAK"

            strcat(str1, str2)

Yields MUNILAK.

Example: Program using strcat() function

/* Program using strcat() function */

#include <stdio.h>

main()

{

        /* Local definitions */

        char source[]="Ramesh";

        char target[10]= "Babu";

        /* Statements */

        strcat(source, target); /* string concatenate function */

        printf("\nSource string is %d", source);

        printf("\nTarget string is %s", target);

} /* main */

OUTPUT

Source string is Ramesh Babu

Target string is Babu

EXPLANATION: In the program source[] is a character variable which holds the data "Ramesh" similarly target[] is a character variable which holds the data "Babu", The strcat() combines both strings and stores in the variable "source" finally print the variable "source" and "target" as mentioned above.

5.4. The strcmp() function

This is a function which compares two strings to find out whether they are same or different. The two strings are compared character by character until the end of one of the string is reached. If the two strings are identical, strcmp() returns a value zero. If they are not equal, it returns the numeric difference between the first non‒matching characters.

Syntax: strcmp(string1, string2);

Description: string1 and string2 are character type arrays or string constants.

Example: Program using strcmp() function.

/* Program using strcmp() function */

#include <stdio.h>

#include <conio.h>

main()

{

* Local definitions */

char name[] = "Kalai",

char name[] = "Malai";

int i,j,k;

/* Statements */

i= strcmp(name, "Kalai"); /* string compare function */

j= strcmp(namel, name);

k=strcmp(name, "Kalai mani");

printf("\n %d %d %d", i, j, k );

} /* main */

OUTPUT

0   1   6

EXPLANATION: In the first strcmp(,) the two strings are same, so it returns zero value. In the second, the first character of the two string is unmatched. So the difference between ASCII value is printed. In the third one, the strings are unmatched. The blank space is unmatched with '\0' character. So the ASCII value difference between '\0' and 'space' is printed.

5.5. The strrev() function

The strrev() function is used to reverse a string. This function takes only one argument and return one argument.

The general form of strrev() function is,

Syntax: strrev(string);

Description: string are characters type arrays or string constants.

Example: Program using strrev() function

/* Program using strrev() function */

#include <stdio.h>

main()

{

        char y[30]; /* Local definition */

        printf ("Enter the string :");

        gets(y);

        printf ("The string reversed is :%s", strrev(y));

} /* main */

INPUT: Enter the string : book

OUTPUT: The string reversed is: koob

EXPLANATION: The function strrev() is used to print the string in reverse order. The program gets the input book then reverse that string as koob and prints the result as output.

5.6. The strchr() Function

The strchr() function returns a pointer to the first occurrence of the low‒ order byte of ch in the string pointed to by str. If no match is found, a null pointer is returned.

Syntax: char *strchr(const char *str, int ch);

Description: Where Char is string, ch is character

Example: Program prints the string is a test

#include <stdio.h>

#include <string.h>

int main(void)

{

         char *p; c='g'

         p = strchr("C Language", ");

         printf(p); printf("%d",c);

         return 0;

}

OUTPUT

C Language

5

5.7. The strlwr() function

The strlwr() function converts all the uppercase characters in that string to lowercase characters. The resultant from strtwr() is stored in the same string.

Syntax: strlwr(string name);

Description: Where string name is string

Example: Program using strlwr() function

#include <stdio.h>

#include <string.h>

int main()

{

char strl]="LOWER CASE";

puts(strlwr(strl)); //converts to lowercase and displays it.

return 0;

}

OUTPUT

lower case

5.8. The strupr() function

The strupr() function converts all the lowercase characters in that string to uppercase characters. The resultant from strupr() is stored in the same string.

Syntax: strlwr(string _name);

Description: Where string_name is string

Example: Program using strupro function

#include <stdio.h>

#include <string.h>

int main()

{

        char str[]="upper case";

        puts(strupr(str1)); //converts to lowercase and displays it.

        return 0;

}

OUTPUT

UPPER CASE

 

Computer Programming C: UNIT II: Arrays and Strings : Tag: Computer Science : C Programming - String Operations


Computer Programming C: UNIT II: Arrays and Strings



Under Subject


Computer Programming C

CS25C01 1st Semester | 2025 Regulation | 1st Semester 2025 Regulation



Related Subjects


English Essentials I

EN25C01 1st Semester | 2025 Regulation | 1st Semester 2025 Regulation


தமிழர் மரபு - Heritage of Tamils

UC25H01 1st Semester | 2025 Regulation | 1st Semester 2025 Regulation


Applied Calculus

MA25C01 Maths 1 M1 - 1st Semester | 2025 Regulation | 1st Semester 2025 Regulation


Applied Physics I

PH25C01 1st Semester | 2025 Regulation | 1st Semester 2025 Regulation


Applied Chemistry I

CY25C01 1st Semester | 2025 Regulation | 1st Semester 2025 Regulation


Makerspace

ME25C04 1st Semester | 2025 Regulation | 1st Semester 2025 Regulation


Computer Programming C

CS25C01 1st Semester | 2025 Regulation | 1st Semester 2025 Regulation


Computer Programming Python

CS25C02 1st Semester | 2025 Regulation | 1st Semester 2025 Regulation


Fundamentals of Electrical and Electronics Engineering

EE25C03 1st Semester EEE Depart | 2025 Regulation | 1st Semester 2025 Regulation


Introduction to Mechanical Engineering

ME25C03 1st Semester Mechanical Dept | 2025 Regulation | 1st Semester 2025 Regulation


Introduction to Civil Engineering

CE25C01 1st Semester Civil, Agri Departments | 2025 Regulation | 1st Semester 2025 Regulation


Essentials of Computing

CS25C03 1st Semester - AIDS, CSE, CSE(CY), IT Department | 2025 Regulation | 1st Semester 2025 Regulation


Applied Physics I Laboratory

PH25C01 1st Semester practical Laboratory Manual | 2025 Regulation | 1st Semester Laboratory 2025 Regulation


Applied Chemistry I Laboratory

CY25C01 1st Semester practical Laboratory Manual | 2025 Regulation | 1st Semester Laboratory 2025 Regulation


Computer Programming C Laboratory

CS25C01 1st Semester EEE, ECE, CSE, CSE(CY), AIDS, IT practical Laboratory Manual | 2025 Regulation | 1st Semester Laboratory 2025 Regulation


Computer Programming Python Laboratory

CS25C02 1st Semester practical Laboratory Manual | 2025 Regulation | 1st Semester Laboratory 2025 Regulation


Engineering Drawing

ME25C01 EEE, Mech, Agri, EEE Depts | 2025 Regulation | 2nd Semester 2025 Regulation


Basic Electronics and Electrical Engineering

EE25C04 1st Semester ECE Dept | 2025 Regulation | 1st Semester 2025 Regulation


Essentials of Computing - Laboratory

CS25C03 1st Semester AIDS, CSE, CSE(CY), IT Depts | practical Laboratory Manual | 2025 Regulation | 1st Semester 2025 Regulation