0% found this document useful (0 votes)
6 views32 pages

Module 13 - Part 1 - String Operations

Module 13 covers string operations in C, including string declaration, initialization, input, and manipulation. It discusses various functions for character and string manipulation, such as those in 'ctype.h' and 'string.h', along with practical examples and exercises. The module also includes problems related to arrays of strings and sorting techniques.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views32 pages

Module 13 - Part 1 - String Operations

Module 13 covers string operations in C, including string declaration, initialization, input, and manipulation. It discusses various functions for character and string manipulation, such as those in 'ctype.h' and 'string.h', along with practical examples and exercises. The module also includes problems related to arrays of strings and sorting techniques.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Module 13 – part 1 – String

operations
BITS Pilani Dr. Ashutosh Bhatia and Dr. Asish Bera
Pilani Campus
Department of Computer Science & Information Systems
Module Overview

• Strings
• Strings Operations

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Strings
• Strings in C are represented by arrays of characters
• End of the string is marked with a special character NUL.
• The corresponding escape sequence character is \0.
• C does not have string data type.

Declaration of strings:
char str[30];
char line[80];

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
String Initialization
char str[9] = “I like C”;
same as
char str[9]={‘I’,‘ ‘,’l’,‘i’,’k’,’e’,‘ ‘,’C’,’\0’};

Q. Is there any difference between following Initialization?


char str[]=“BITS”;
char str[4]= “BITS”;

Ans: Yes, in second declaration there is no null character

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Printing Strings
char text[]=“C Programming”;
printf("%s\n",text);

Output???
C Programming

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Reading a String (2-1)
Using scanf()
char text[30];
printf(“Enter a string: ”);
scanf(“%s”,text);
printf(“The string is : %s”,text);

Sample output:
Enter a string: hello
The string is: hello
-----------------------------------------
Enter a string: hello how are you
The string is: hello
Note: scanf() takes string without blank space

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Reading a String (2-2)
char text[30];
printf(“Enter a string: ”);
scanf(“%[a-z]s”, text);
printf(“The string is : %s”,text);

Sample output:
Enter a string: hello
The string is: hello
-----------------------------------------
Enter a string: hello123
The string is: hello
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Single Line input
char text[80];
printf(“Enter a string: ”);
scanf(“%[^\n]s”,text);/*newline terminated string */
printf(“The string is : %s”,text);

Sample output:
Enter a string: hello how are you
The string is: hello how are you

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Multi line Input
char text[180];
printf(“Enter a string terminate with ~: ”);
scanf(“%[^~]s”,text);
printf(“The string is : %s”,text);

Note: After ^ any character can be used to


terminate the input.
Sample output:
Enter a string terminate with ~: hello how are
you. ~
The string is: hello how are you.

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Input String using gets()
char str[200];
printf(“Enter a string :”);
gets(str);
printf(“The string is :%s”,str);

Output
Enter a string :C programming
The string is : C programming

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Character Manipulation in the
String – eliminate spaces
int main()
{ char s[80],ws[80];
int i,j;
printf(“Enter the text:\n”);
gets(s); /* reading text from user */
for(i=0,j=0; s[i]!=‘\0‘; i++)
{ if(s[i]!=‘ ‘)
ws[j++] = s[i];
}
ws[j]=‘\0’;

printf(“The text without blank space is:\n”);


puts(ws); /* printing text on monitor */
return;
}

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Important Character functions
in “ctype.h”
isdigit(c)/*Returns a nonzero if c is a digit*/

islower(c) /* Returns a nonzero if c is a


lower case alphabetic character */
isalpha(c)/*Returns a nonzero if c is an
alphabet*/
isspace(c) /*Returns a nonzero for blanks */
isupper(c) /*Returns a nonzero if c is capital
letter*/
toupper(c) /* Returns upper case of c */

tolower(c) /* Returns lower case of c */

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
String Manipulation functions
in string.h
strcpy(s1,s2) /* copies s2 into s1 */

strcat(s1,s2) /* concatenates s2 to s1 */

strlen(s) /* returns the length of s */

strcmp(s1,s2)/*returns 0 if s1 and s2 are same


returns less then 0 if s1<s2
returns greater than 0 if s1>s2 */

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Other functions in string.h

atof(): Converts an ASCII char s1[] = "+1776.23";


string to its floating-point double my_value = atof(s1);
equivalent (type double)

atoi(): Converts an ASCII char s2[] = "-23.5";


string to its integer equivalent int my_value = atoi(s2);

strncat(): Works like strcat, char s1[50] = "Hello, world!";


but concatenates only a char s2[] = "Bye now!";
strncat (s1, s2, 3);
specified number of
characters.

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Other functions in string.h

strncmp(): Works like strcmp, char s1[] = "dogberry";


but compares only a specified char s2[] = "dogwood";
number of characters of both int comp = strncmp (s1, s2, 3);
strings.
strncpy(): Works like strcpy, char dest[50];
but copies only a specified char src[] = "C Program";
number of characters. strncpy (dest, src, 3);

strstr(): Tests whether a char s1[] = "Got food?";


substring is present in a larger char s2[] = "foo";
string. Returns a pointer to the
if (strstr (s1, s2))
first occurrence of the substring
printf("'%s' is a substring of
in the larger string, or zero if
'%s'.\n", s2, s1);
the substring is not present.

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Implementation of strlen()
int n = 0;
char text[100],c;
while((c = getchar())!=‘\n’&& n<99)
text[n++] = c;

text[n++]=‘\0’;
printf(“Length of text : %d”,n);

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Implementation of strcat()
void main() /* s2 is concatenated after s1 */
{ char s1[100],s2[100];
int i = 0,j = 0;
printf("Enter first string\n");
scanf("%[^\n]s",s1); getchar();
printf("Enter second string\n");
scanf("%[^\n]s",s2);
while(s1[i++] != '\0'); i--;
while(s2[j] != '\0')
s1[i++] = s2[j++];
s1[i] = '\0';
printf("\n Final string is:%s",s1);
}

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Palindrome problem
void main()
{ char str[80];
int left,right,i,len,flag = 1;
printf("Enter a string");
for(i = 0;(str[i] = getchar())!='\n';++i);
len = i-1;
for(left = 0,right = len; left < right; ++left,--right)
{ if(str[left]!= str[right])
{ flag = 0;
break;
}
}
if(flag)printf("\n String is palindrome");
else
printf("\n String is not a palindrome");
}

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Word counting Problem
void main()
{ char text[40];
int i = 0,count = 0;
printf("Enter a string:");
gets(text);
while(text[i]!='\0')
{
while(isspace(text[i]))
i++; /* Repeat till first non blank character */
if(text[i]!='\0')
{ count++;
while(!isspace(text[i])&& text[i]!='\0')
i++; /* Repeat till first blank character */

}
}
printf("The number of words in the string is %d",count);
}
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Arrays of Strings
Declaration:
char name[5][30];
Five strings each contains maximum thirty characters.

Initialization:
char[5][10]={“One”,”Two”,”Three”,”Four”,”Five”};

Other valid declarations


char[][]={“One”,”Two”,”Three”,”Four”,”Five”};

char[5][]={“One”,”Two”,”Three”,”Four”,”Five”};

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Array of Strings

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Array of Strings using Pointers

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Exercise
int main () {

char *cityPtr[] = {"Chennai", "Kolkata", "Mumbai",


"New Delhi"};

for (int i = 0; i < 4; i++)


printf("\n cityPtr[%d] = %s", i, cityPtr[i] );

return 0;
}

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
String Arrays: Reading and
Displaying
void main()
{ char name[5][30];
printf(“\n Enter five strings”);
/* Reading strings */
for(i=0;i<5; i++)
scanf(“%s”,s[i]);
/* Printing strings */
for(i=0;i<5; i++)
printf(“\n%s”,name[i]);
}

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Problem 3: Array of Strings
Problem Statement: Write a C program that will read and store
the details of a list of students in the format
ID NAME MARKS

And produce the following output


1. Alphabetical list of Names, ID’s and Marks.
2. List sorted on ID’s
3. List sorted on Marks

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Implementation (1-3)
#define N 5
#include<stdio.h>
#include<string.h>
int main()
{
char names[N][30],marks[N][10];
char id[N][12],temp[30];
int i,j;
/* Reading Student Details */
printf("Enter Student ID NAME and MARKS \n");
for(i = 0; i<N; i++)
scanf("%s %s %s",id[i],names[i],marks[i]);

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Implementation (2-3)
/* Alphabetical Ordering of Names */
for(i=1; i<=N-1; i++)
for(j=1; j<=N-i; j++)
if(strcmp(names[j-1],names[j])>0)
{ strcpy(temp,names[j-1]);
strcpy(names[j-1], names[j]);
strcpy(names[j], temp);
/* Swapping of marks */
strcpy(temp,marks[j-1]);
strcpy(marks[j-1], marks[j]);
strcpy(marks[j], temp);

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Implementation (3-3)
/* Swapping of ID’s */
strcpy(temp,id[j-1]);
strcpy(id[j-1], id[j]);
strcpy(id[j], temp);
}
printf("ALPHABETICAL LIST OF ID NAME &
MARKS");
for(i=0;i<N;i++)
printf("%s\t%s\t %s\n",id[i],names[i],marks[i]);
return;
}

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
ID wise Sorting (ID is a string)
for(i=1;i<=N-1;i++)
{ for(j=1; j<=N-i; j++)
{ if(strcmp(id[j-1],id[j])>0)
{ strcpy(temp,id[j-1]);
strcpy(id[j-1], id[j]);
strcpy(id[j], temp);
/* Swaping of marks */
strcpy(temp,marks[j-1]);
strcpy(marks[j-1], marks[j]);
strcpy(marks[j], temp);
/* Swaping of names */
strcpy(temp,names[j-1]);
strcpy(names[j-1], names[j]);
strcpy(names[j], temp);
}
}
}

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Home Exercise 1
1) Write a C program to implement strcpy()

2) Write a C program to implement strcmp()

3) Write a C program to search a string from an array of strings.

4) Write a C program that copies the unique words among the set of
words into another memory location.

5) Write a C program which will read a line of text and rewrite it in the
alphabetical order.

6) Write a C program to replace a particular word by another word in a


given string. Both the words are provided by the user at run time.
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Home Exercise 2
1) Write a C program that counts the number of vowels,
consonants, digits and other symbols in a given line of text.

2) Write a C program to reverse a string. Try not to use an extra


string and modify the source string to store the reversed string.
Number of exchanges should be minimal.

3) Write a C Program to separate a given string into two strings.


All the odd positioned characters are stored in the first string
and even positioned characters in the second string.

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

You might also like