0% found this document useful (0 votes)
54 views16 pages

Unit 4 - I Strings v1.5

This document provides lecture notes on strings in C programming. It discusses declaring and initializing strings, reading strings from the user, writing strings to the screen, and performing operations on strings without built-in functions. These operations include finding the length of a string, copying a string, concatenating strings, reversing a string, and comparing strings. It also provides an example application that sorts names stored in a 2D array and discusses built-in string handling functions in C.

Uploaded by

amarjeet kumar
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)
54 views16 pages

Unit 4 - I Strings v1.5

This document provides lecture notes on strings in C programming. It discusses declaring and initializing strings, reading strings from the user, writing strings to the screen, and performing operations on strings without built-in functions. These operations include finding the length of a string, copying a string, concatenating strings, reversing a string, and comparing strings. It also provides an example application that sorts names stored in a 2D array and discusses built-in string handling functions in C.

Uploaded by

amarjeet kumar
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/ 16

TM's

Lecture Notes in C Programming (LNCP)


Unit 4 Part 1
Strings
Ver. 1.5
TM’s C Programming Lecture Notes Ver. 1.5 Strings

Contents
1. Strings in C 3
1.1 Common operations on strings 3
1.2 Declaring and initializing strings 3
Initializing: 3

2. Reading string from user 4

3. Writing strings to screen 6

4. Operations on Strings without using built-in functions 7


4.1 Finding the length of a string. 7
4.2 Copy String without using built-in function strcpy() 7
4.3 Concatenate Two Strings Without Using built-in function strcat() 8
4.4 Reversing a string 9
4.5 Comparing two strings 10

5. Application program: Sorting names stored in a 2-D array 11

6. String handling functions in C (SLE) 12

2 (For non-commercial educational use only)


TM’s C Programming Lecture Notes Ver. 1.5 Strings

​1. Strings in C
❑ In C, String is a sequence of characters treated as a single data item.
❑ E.g. “Hello world”, “Well done”
❑ Note: double quotes not part of string data.
❑ In C, Strings are represented using character arrays.
❑ E.g: char name[20];

​1.1 Common operations on strings


❑ Reading & Writing strings (I/O)
❑ Combining strings
❑ Copying Strings
❑ Comparing strings for equality
❑ Extracting portion of a string(sub-string)

​1.2 Declaring and initializing strings


❑ General format:
char string_name[size];

E.g. char name[20], city[20];

​Initializing:
❑ E.g.1: char city[9] = “New York”;
❑ E.g. 2: char city[9] = {‘N’,’e’,’w’,'',’Y’,’o’,’r’,’k’,’\0’};
❑ Null character ‘\0’ inserted by compiler in e.g.1.
❑ Specify array size considering ‘\0’ also.
❑ E.g.: char city[9] = “New York”;

❑ char str[9] = “Good”; // Valid initialization

char str1[9] ;
str1 = “Good”; // Error: Not allowed to assignment like this in C
❑ Null character(\0) marks the end-of-string.
PRG416:String: compile time initialization

// String: compile time initialization


#include<stdio.h>
int main()
{
// Two ways to initialize, which are equivalent
char str1[10] = "New York";

3 (For non-commercial educational use only)


TM’s C Programming Lecture Notes Ver. 1.5 Strings

char str2[10] = {'N','e','w','','Y','o','r','k','\0'};


printf("str1:\t%s\n",str1);
printf("str2:\t%s\n",str2);
return 0;
}
Output:
str1: New York
str2: New York

​2. Reading string from user


❑ Using scanf() function.
char address[9];
scanf("%s", address);

❑ If user enters New York for above code, it is stored as:

‘?’s may be unknown random/garbage characters


❑ Normally scanf stops reading input when whitespace is encountered.
❑ Try reading as two string:
scanf("%s %s", addr1,addr2);
Using scanf function: Reading specified number of characters
char address[9];
scanf("%4s", address); // Only first 4 characters of input string read.
❑ If user enters London, only 4 characters read:

PRG417:String input from user(%ws)

// String input from user(%ws)


#include<stdio.h>
void main()
{
char str1[10];
char str2[10];
printf("Enter the string:");
scanf("%s",str1);
scanf("%4s",str2);
printf("str1:\t%s\n",str1);
printf("str2:\t%s\n",str2);
}
o/p
Enter the string:hello world
str1: hello
str2: worl // w=4 so only 4 chars read from user

4 (For non-commercial educational use only)


TM’s C Programming Lecture Notes Ver. 1.5 Strings

❑ General format
scanf(“%ws”,string_variable);

❑ If entered string longer than w, only w characters read.


❑ Remaining can be read by another scanf call.

Using scanf function: Reading a line of text having spaces.

char str[50];
printf("Enter the line of text:");
scanf("%[^\n]",str);
printf("Text is: %s",str);

❑ Note: The above method may not work well with all compilers.
❑ Reading string from user(prg419)
❑ gets() function to read a line.
char str[50];
printf("Enter the line of text:");
gets(str); // 1
printf("Text is:%s\n",str); // 2
❑ 1 & 2 may be combined as:
printf("Text is:%s\n", gets(str));

PRG419:String input: reading a line using gets function


// String input: reading a line using gets function
#include<stdio.h>
void main()
{
char str[20];
printf("Enter the line of text:");
gets(str); // not a reliable function with all compilers
printf("Text is:%s\n",str);
}
o/p:
Enter the line of text:hello world
Text is:hello world

❑ Note: May not work well in all compilers.


Reading a character from user
❑ Using scanf function
char ch;
scanf(“%c”,&ch);

❑ Using getchar function


char ch2;
ch2= getchar();

5 (For non-commercial educational use only)


TM’s C Programming Lecture Notes Ver. 1.5 Strings

​3. Writing strings to screen


❑ Function: printf ()
char str[6] = "Hello";
printf("String is: %s",str);

❑ Specifying width and precision: %w.ps (e.g. %6.5s)

❑ printf(“String is: %9.5s”,str); //9🡺 reserved screen width, 5🡺 no. of chars to display

❑ printf(“String is: %-9.5s”,str); // -9 🡺 left align

❑ Writing strings to screen(prg420)

char str[6] = "Hello";


printf("String: %9.5s\n",str);
printf("String: %s\n",str);
printf("String: %9.2s\n",str);
Output:
String: Hello
String:Hello
String: He

Function: puts ==> outputs given string to screen


char str[15] = "Hello World";
puts(str);
Output:
Hello World

Function: putchar : Outputs given character to screen


char ch = 'A';
putchar(ch);
putchar('B');
Output:
AB

6 (For non-commercial educational use only)


TM’s C Programming Lecture Notes Ver. 1.5 Strings

​4. Operations on Strings without using built-in functions


​4.1 Finding the length of a string.
Approach: Length is initialized to 0. Then a loop is run checking every character in the array from start. For every
character other ‘\0’ length is incremented by one. Loop stops when the first ‘\0’ is encountered. So we get the count of
how many characters other than ‘\0’ are found. That is the length of the string.
// Finding length of a string
#include <stdio.h>
int main()
{
char s[20],i,length;

printf("Enter first string: ");


scanf("%s", s);

// calculate the length of string s1


length = 0;
while(s[length] != '\0')
{
length++;
}

printf("Length = %d", length);

return 0;
}

Output:
Enter first string: hello
Length of the entered string = 5

​4.2 Copy String without using built-in function strcpy()


Approach: We have two arrays. Source array stores the string entered by the user. Destination array is the array to
which this string is to be copied. Run a loop to take each character from the source array and put it in the corresponding
location of the destination array. The loop stops when ‘\0’ is found in the source array.
Once out of the loop add a ‘\0’ character at the end of characters stored in the destination array to mark the end of the
string.
#include<stdio.h>
int main()
{
char s1[100], s2[100], i;
printf("Enter string s1: ");
scanf("%s",s1);

// From source string, each character is copied


// to corresponding location in destination.

7 (For non-commercial educational use only)


TM’s C Programming Lecture Notes Ver. 1.5 Strings

for(i =0; s1[i]!='\0';++i)


{
s2[i]= s1[i];
}
s2[i]='\0'; // Adding null character for the new copy.

printf("String s2: %s", s2);


return 0;
}

Output:
Enter string s1: hello
String s2: hello


​4.3 Concatenate Two Strings Without Using built-in function strcat()
Approach: Find the index of ‘\0’ character in the destination array by running a loop.
for(i =0; s1[i]!='\0';++i);
Now variable i has the index value of ‘\0’ in string s1. In a new loop take each character from source array and put in
to destination array s1 at index starting from i,i+1….etc. until all characters of source string s2 are copied. At last put a
‘\0’ at the end of all characters in destination array s1.

#include<stdio.h>
int main()
{
char s1[100], s2[100], i, j;
printf("Enter first string: ");
scanf("%s", s1);

printf("Enter second string: ");


scanf("%s", s2);

// calculate the length of string s1


// and store it in i
for(i =0; s1[i]!='\0';i++);

// Now ‘i' has the length of s1(same as the index of ‘\0’).


// s[i] has '\0' of string s1
// Copy characters from string s2 to s1[i] onwards
for(j =0; s2[j]!='\0';j++,i++)
{
s1[i]= s2[j];

8 (For non-commercial educational use only)


TM’s C Programming Lecture Notes Ver. 1.5 Strings

s1[i]='\0';
printf("After concatenation: %s", s1);

return0;
}

Output:
Enter first string: hello
Enter second string: world!
After concatenation: helloworld!

​4.4 Reversing a string


Approach: First length of string is found using the previous method. In a loop, swap 1st and last characters, then 2nd and
second last character & so...on. This process is repeated length/2 times and we get the string in reverse order.
E.g: hello
1. First, characters h and o are swapped. Resultant string is: oellh
2. Next, e and l are swapped. Result is: olleh. Length/2 is 2. We swapped two times and we stopped. Output is the
reverse of the original string.
// Reversing string without additional array
#include <stdio.h>

int main(){

char str[20];

printf("Enter the word\n");


scanf("%s",str);

//Reversing the string copy


int len,i;
char temp;

// Finding length of string


len = 0;
while(str[len]!='\0') len++;

printf("strlen is %d\n",len);

// Reversing the string by exchanging


// characters from both ends
for(i = 0;i<len/2;i++)
{
temp = str[i];
str[i] = str[len-i-1];
str[len-i-1] = temp;
}

9 (For non-commercial educational use only)


TM’s C Programming Lecture Notes Ver. 1.5 Strings

printf("Reversed string is: %s\n",str);

return 0;
}
Output:
Enter the word
welcome
strlen is 7
Reversed string is: emoclew

​4.5 Comparing two strings

//Comparing two strings


//If both are same result==> 0
//If 1st precedes 2nd in alphabetical order, result ==> -1
//If 2nd precedes 1st in alphabetical order, result ==> 1

#include <stdio.h>

int main()
{
char s1[100], s2[100], i, j;

printf("Enter first string: ");


scanf("%s", s1);

printf("Enter second string: ");


scanf("%s", s2);

for(i = 0; s1[i]!='\0' && s2[i]!='\0'; i++)


{
if(s1[i] < s2[i])
{
// s1 should come first alphabetically
printf("-1") ;
return 0;
}

if(s1[i] > s2[i] )


{
// s2 should come first alphabetically
printf("1") ;
return 0;
}
} // end of loop

if(s1[i] == '\0' && s2[i] == '\0') //if both strings are over
{
//Both strings are equal(same)
printf("0") ;
}

10 (For non-commercial educational use only)


TM’s C Programming Lecture Notes Ver. 1.5 Strings

else if(s1[i] == '\0') // If Only s1 is over


printf("-1") ; // s1 should come first alphabetically
else if(s2[i] == '\0')// If only s2 is over
printf("1") ; // s2 should come first alphabetically

return 0;
}

O/p:
1.
Enter first string: abcd
Enter second string: abcd
0
2.
Enter first string: abCd
Enter second string: abcd
-1
3.
Enter first string: abcd
Enter second string: abCd
1
4.
Enter first string: abcd
Enter second string: abcdef
-1
5.
Enter first string: abcdef
Enter second string: abcd
1

​5. Application program: Sorting names stored in a 2-D array


// Sorting names of n students in alphabetical order
#include <stdio.h>
int main()
{
char names[10][20]; // 2-D array to store all names
char temp[20]; // For 1 name exchange
int i,j,n;

printf("How many names: ");


scanf("%d", &n);

for(i=0;i<n;i++)
{
printf("Enter next name:");
scanf("%s",names[i]);
}

printf("The given names are:\n");


for(i=0;i<n;i++)
{
printf("%s\n",names[i]);

11 (For non-commercial educational use only)


TM’s C Programming Lecture Notes Ver. 1.5 Strings

// Alphabetical order sorting


for(i = 0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if( strcmp(names[j],names[j+1]) > 0)
{
/*2nd name should appear before 1st in alphabetical order
we swap */
strcpy(temp,names[j]);
strcpy(names[j],names[j+1]);
strcpy(names[j+1],temp);
}
}
}

printf("The sorted names are:\n");


for(i=0;i<n;i++)
{
printf("%s\n",names[i]);
}

return 0;
}

Sample I/O
How many names: 5
Enter next name:Rahul
Enter next name:Rohan
Enter next name:Amit
Enter next name:Shashank
Enter next name:Balu

The given names are:


Rahul
Rohan
Amit
Shashank
Balu

The sorted names are:


Amit
Balu
Rahul
Rohan
Shashank

​6. String handling functions in C (SLE)


❑ Following library functions coming as part of C for string handling.
❑ strcat() 🡺 Concatenates two strings.

12 (For non-commercial educational use only)


TM’s C Programming Lecture Notes Ver. 1.5 Strings

❑ strcmp() 🡺 Compares two strings.


❑ strcpy() 🡺 Copies one string to another.
❑ strlen() 🡺 Finds length of string.
❑ strrev() 🡺 reverse a string

1. strcat()
Concatenates two strings.

Usage: strcat(str1,str2);

● Str2 is appended at the end of str1. The combined string is stored in


str1.
● Make sure str1 is large enough to contain concatenation of str1 and str2.

PRG422: String handling functions: strcat


// String handling functions
// strcat
#include<stdio.h>
#include<string.h>
void main()
{
char str1[15] = "Hello";
char str2[6] = "World";
strcat(str1,str2);
puts(str1);
}

o/p:
HelloWorld

PRG423:Concatenates user entered strings: strcat

// String handling functions


// strcat
// Concatenates user entered strings
#include<stdio.h>
#include<string.h>
void main()
{
char str1[20];
char str2[20];
printf("Enter string 1:");
gets(str1);
printf("Enter string 2:");
gets(str2);
strcat(str1,str2);
printf("Concatenated string:");
puts(str1);

13 (For non-commercial educational use only)


TM’s C Programming Lecture Notes Ver. 1.5 Strings

o/p:
Enter string 1:hello
Enter string 2:world
Concatenated string:helloworld

2. strcmp() 🡺 Compares two strings.


❑ Usage: strcmp(string1,string2);
❑ Return values:
0 🡺 if both strings are same
<0 🡺 if string1 precedes string2 alphabetically (-1 mostly)
>0 🡺 if string2 precedes string1 alphabetically (1 mostly)

❑ Some implementations return the difference of the ASCII values of first mismatching characters.
i.e strcmp("their","there"); // return -9 which is the difference of ascii values of i and r.

❑ Example for strcmp


char str1[15] = "ABCD";
char str2[10] = "abcd";

int r = strcmp(str1,str2); // r = -1
r = strcmp("abcd","abcd"); // r=0
r = strcmp("abcd","abCd"); // r=1
r = strcmp("abcd","abfd"); // r=-1
r = strcmp("abfd","abcd"); // r=1
r = strcmp("ABCD","abcd"); // r=-1

3. strcpy() 🡺 Copy string2 to string1(second to first string)


❑ Usage: strcpy(string1,string2);
❑ String1 should be large enough to contain string2
char str1[15];
char str2[15] = "Hello World";
strcpy(str1,str2); // str1 🡺 "Hello World"

PRG425:String handling functions: strcpy

// String handling functions: strcpy


// Copies the second string to first
#include<stdio.h>
#include<string.h>
void main()
{
char str1[15];
char str2[15] = "Hello World";
strcpy(str1,str2);
printf("Copied string:");
puts(str1);

14 (For non-commercial educational use only)


TM’s C Programming Lecture Notes Ver. 1.5 Strings

}
o/p
Copied string: Hello World

4. strlen() 🡺 Returns the length of a string.

🡺 length = number of characters in the string


❑ Usage: len = strlen(string);
❑ E.g.
char str[15] = "Hello";
int n= strlen(str); // n ==> 5
❑ Null character (\0) not considered for length calculation

❑ strlen() e.g. program


void main()
{
char str[15] = "Hello World";
int len;
len = strlen(str);
printf("Length = %d",len);
}
Output:
Length = 11

5. strrev() 🡺 reverse a string


❑ Usage: strrev(string);
❑ E.g.
char str[15] = "Hello";
strrev(str); // str🡺 "olleH"

PRG426: String handling functions: strrev


// String handling functions: strrev
// Reverse the given string
#include<stdio.h>
#include<string.h>
int main()
{
char str[20];
printf("Enter a string: ");
gets(str);
strrev(str);
printf("Reversed string is: %s",str);

return 0;
}

o/p:
Enter a string: hello

15 (For non-commercial educational use only)


TM’s C Programming Lecture Notes Ver. 1.5 Strings

Reversed string is: olleh

16 (For non-commercial educational use only)

You might also like