Module 8 – part 2 – String
operations
BITS Pilani
Pilani Campus
Department of Computer Science & Information Systems
Module Overview
• Character Arrays
• Strings
• Strings Operations
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus
Character Arrays
Character (Char) Arrays
char color[3] = "RED"; R E D
char color[ ] = "RED";
R E D \0
Are they the same?
Character arrays are the way to represent strings in C.
Each string typically ends with a NULL character "\0".
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 NULL.
• 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
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
Char Arrays contd...
Write a C program which reads a 1D char array, converts all
elements to uppercase, and then displays the converted array.
Hint: use toupper(ch) of <ctype.h>
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Lower Case to Upper Case
using char array
#include <stdio.h> name[i]='\0'; ????
#include <ctype.h> size = i;
int main(){ printf("\nName is %s", name);
int size,i=0; for(i=0;i<size;i++)
char name[50]; putchar(toupper(name[i]));
name[0]=getchar(); return 0;
while(name[i]!='\n') }
{
i++;
name[i]=getchar();
}
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
getchar() and putchar()
• int getchar(void);
- getchar is a standard C library function (requires stdio.h) that
reads a single character from the standard input (usually the
keyboard) and returns the character as an integer (ASCII
value). It's commonly used for basic character input in
console-based programs.
• int putchar(int character);
- putchar is a standard library function (requires stdio.h) in C and
C++ used for output operations. It is used to write a single
character to the standard output, typically the console or
terminal.
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Char Arrays contd…
Modify the previous code to use scanf()/printf() in place of
getchar()/putchar()
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Lower Case to Upper Case
using char array
#include <stdio.h> name[i]='\0';
#include <ctype.h> size = i;
int main(){ printf("\nName is %s",name);
int size,i=0; for(i=0;i<size;i++)
char name[50]; printf(“%c”,toupper(name[i]))
scanf(“%c”,&name[0]); ;
while(name[i]!='\n') return 0;
{ }
i++;
scanf(“%c”,&name[i]);
}
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Reading a String
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
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 (using
custom delimiter for scanf)
char text[180];
printf(“Enter a string terminating 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 terminating with ~: hello how
are you. ~
The string is: hello how are you.
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Using gets/puts
Note:
#include<stdio.h> • It is not required to
int main() explicitly insert ‘\0’
{ character at the end of
char str[20]; each character array
printf("Enter a string: "); while using gets().
gets(str); • It automatically adds so.
printf("The string is %s",str);
puts(str);
return 0;
}
Output
Enter a string :C programming
The string is : C programming
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Input String using gets() with a
larger number of characters
char str[20];
printf(“Enter a string :”);
gets(str);
printf("The string is %s",str);
puts(str);
Output
Warning!! gets() is deprecated.. Use fgets() instead
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Input String using fgets()
char str[20];
printf("Enter a string: ");
if (fgets(str, sizeof(str), stdin) != NULL) {
for (int i = 0; str[i] != '\0'; i++) {
if (str[i] == '\n') {
str[i] = '\0';
break;
}
}
printf("The string is: %s\n", str);
} else {
printf("Error reading input.\n");
}
Output:
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 0;
}
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Character Manipulation in the String
– eliminate spaces – using fgets
int main()
{
char s[80],ws[80];
int i,j;
printf("Enter the text:\n");
fgets(s, sizeof(s), stdin); /* reading text
from user */
for(i=0,j=0; s[i]!='\0'; i++)
{ if(s[i]!=' ' && s[i]!=‘\n')
ws[j++] = s[i];
}
ws[j]='\0';
printf("The text without blank space is:\n");
puts(ws); /* printing text on monitor */
return 0;
}
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
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
Try this!
char s1[] = "9"; char s2[] = "10";
int res1 = strcmp(s1, s2);
int res2 = strcmp(s2, s1);
char s1[] = “09"; char s2[] = "10";
int res1 = strcmp(s1, s2);
int res2 = strcmp(s2, 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
Homework
Try replacing gets with fgets in the previous example!!
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Other functions in
string.h/stdlib.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 int my_value = atoi(s2);
equivalent
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 first occurrence of the if (strstr (s1, s2))
printf("'%s' is a substring of
substring in the larger string,
'%s'.\n", s2, s1);
or zero if the substring is not
present.
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 name[5][10]={“One”,”Two”,”Three”,”Four”,”Five”};
Invalid 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
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”,name[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()
1) Write a C program to implement strcmp()
1) Write a C program to search a string from an array of strings.
1) Write a C program that copies the unique words among the set of
words into another memory location.
1) Write a C program which will read a line of text and rewrite it in the
alphabetical order.
1) 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.
1) 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.
1) 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
Thank you
Q&A