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

UNIT-3 Strings

This document discusses strings in C programming. It defines strings and explains how they are stored and manipulated in memory. It also describes common string functions like strcpy(), strcat(), strlen() and how to declare and initialize strings.

Uploaded by

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

UNIT-3 Strings

This document discusses strings in C programming. It defines strings and explains how they are stored and manipulated in memory. It also describes common string functions like strcpy(), strcat(), strlen() and how to declare and initialize strings.

Uploaded by

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

Strings

Introduction to strings
• The string can be defined as the one-dimensional array of
characters terminated by a null ('\0').
• The character array or the string is used to manipulate text
such as word or sentences.
• Each character in the array occupies one byte of memory, and
the last character must always be 0.
• The termination character ('\0') is important in a string since it
is the only way to identify where the string ends.
• When we define a string as char s[10], the character s[10] is
implicitly initialized with the null in the memory.
Declaring and Initializing a String:

There are two ways to declare and Initialize


a string in c language.

• By char array
• By string literal
• By char array
char c[] = {'a', 'b', 'c', 'd', '\0'};

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

• By string literal

char c[] = "abcd";

char c[50] = "abcd";


Let's take another example:

char c[5] = "abcde";

Here, we are trying to assign 6 characters (the last


character is '\0') to a char array having 5 characters.
This is bad and you should never do this.
Read String from the user
• You can use the scanf() function to read a string.

• The scanf() function reads the sequence of characters


until it encounters whitespace (space, newline, tab,
etc.).

Example 1: scanf() to read a string


#include <stdio.h>
int main() Output
{
char name[20]; Enter name: Dennis Ritchie
Your name is Dennis.
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}
Even though Dennis Ritchie was entered in the above
program, only "Dennis" was stored in the name string.
It's because there was a space after Dennis.

we have used the code name instead of &name with


scanf()

scanf("%s", name);

This is because name is a char array, and we know that


array names decay to pointers in C.
Thus, the variable name in scanf() already
points to the address of the first element in
the string, which is why we don't need to use
&.
Example 2: fgets() and puts()

#include <stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
fgets(name, sizeof(name), stdin); // read string
printf("Name: ");
puts(name); // display string
return 0;
}
OUTPUT:

Enter name: Hello Guys!.. ALL THE BEST


Name: Hello Guys!.. ALL THE BEST
• Here, we have used fgets() function to read a string from
the user.

fgets(name, sizeof(name), stdlin); // read string

• The sizeof(name) results to 30. Hence, we can take a


maximum of 30 characters as input which is the size of the
name string.

• To print the string, we have used


puts(name);.
String Manipulation(Handling) Functions:--

C supports a large number of string handling functions in


the standard library "string.h".

Some Commonly used functions are:--


Function Name Description
strlen(string_name) Returns the length of string _name.

Copies the contents of string s2 to string


strcpy(s1, s2)
s1.

Compares the first string with the second


strcmp(str1, str2)
string. If strings are the same it returns 0.

Concat s1 string with s2 string and the


strcat(s1, s2)
result is stored in the first string.

strlwr() Converts string to lowercase.

strupr() Converts string to uppercase.


strlen()
The strlen() function takes a string as an argument and
returns its length. The returned value is an unsigned integer
type.
//Program to use length strlen()
#include <stdio.h>
#include <strings.h> OUTPUT:--
int main() Enter the String: Welcome to Artificial Intelligence
{
char name[20]; The length of Given String --Welcome to Artifici --is:19
printf("Enter the String: ");
fgets(name,sizeof(name),stdin);

printf("\n The length of Given String --%s-- is:%d",name,strlen(name));

return 0;
}
strcpy()
This function copies contents of one string into another
string.
strcpy( str1, str2) – It copies contents of str2 into str1.

strcpy( str2, str1) – It copies contents of str1 into str2.

• If destination string length is less than source string,


entire source string value won’t be copied into
destination string.
• For example, consider destination string length is 20 and
source string length is 30. Then, only 20 characters from
source string will be copied into destination string and
remaining 10 characters won’t be copied and will be
truncated.
//Program to use Copy strcpy()

#include <stdio.h> OUTPUT:---


#include <strings.h> Enter the String to copy: RCE, Eluru
int main()
{ Copied String is:----RCE, Eluru
char string1[20], copy_str[20] ;

printf("Enter the String to copy: ");


fgets(string1,sizeof(string1),stdin);

strcpy(copy_str,string1);

printf("\n Copied String is:----%s",copy_str);


return 0;
}
strcat( )

This function concatenates two given strings.

strcat( str2, str1 ); - str1 is concatenated at the end of str2.

strcat( str1, str2 ); - str2 is concatenated at the end of str1.


//Program to use Concatenate strcat()
#include <stdio.h>
OUTPUT:--
#include <strings.h>
int main() Enter the String1 : RCE, Eluru
{ Enter the String2 : 534007
char string1[20], string2[20] ; Concatenated String is:-----
RCE, Eluru
534007
printf("Enter the String1 : ");
fgets(string1,sizeof(string1),stdin);

printf("\n Enter the String2:");


fgets(string2,sizeof(string2),stdin);

strcat(string1,string2);

printf("\n Concatenated String is:-----\n%s",string1);


return 0;
}
strcmp()

This function in C compares two given strings and

• returns zero if they are same.


• If length of string1 < string2, it returns < 0 value.
• If length of string1 > string2, it returns > 0 value.

Syntax : strcmp(string1,string2);

strcmp( ) function is case sensitive. i.e., “A” and “a” are


treated as different characters.
//Program to use strcmp()

#include <stdio.h>
#include <string.h>
int main()
{
char string1[20], string2[20] ;

printf("Enter the String1 : ");


fgets(string1,sizeof(string1),stdin);

printf("\n Enter the String2:");


fgets(string2,sizeof(string2),stdin);

printf("\nComparision of Strings is:\n%d",


strcmp(string1,string2));
return 0;
}
OUTPUT:---

Enter the String1 : RCE


Enter the String2:REC
Comparision of Strings is:
-2
strlwr():

This function converts a given string into lowercase.

Syntax:
strlwr(string);
Example :
char str[ ] = “MODIFY “;
printf(“%s\n”, strlwr (str));
Output :
modify
strupr():

This function converts a given string into uppercase.

Syntax :
strupr(string);

Example :
char str[ ] = “modify “;
printf(“%s\n”, strupr(str));
Output :
MODIFY
strrev():

This function reverses a given string in C language.

Syntax :
strrev(string);
Example:
char name[20]=”RCEE”; then
strrev(name)= EECR
Implementation of string manipulation operations without library
function.
a) Copy b) Concatenate c) Length

//Copying the string without using strcpy()


#include <stdio.h>
int main()
{
char s1[100], s2[100], i; OUTPUT:--
printf("Enter string s1: ");
fgets(s1, sizeof(s1), stdin); Enter string s1: hello RCE!
String s2(Copied) is: hello RCE!
for (i = 0; s1[i] != '\0'; ++i) {
s2[i] = s1[i];
}

s2[i] = '\0';
printf("String s2(Copied) is: %s", s2);
return 0;
}
//Program on String Concatenation without using library Function
#include <stdio.h>
int main()
{
char s1[50], s2[50] ;
int i, j;

printf("\n Enter the First String:");


fgets(s1,sizeof(s1),stdin);

printf("\n Enter the Second String:");


fgets(s2,sizeof(s2),stdin);

// Finding the length of first String


i = 0;
while (s1[i] != '\0') {
i++;
}

// concatenate s2 to s1
for (j = 0; s2[j] != '\0'; ++j, ++i) {
s1[i] = s2[j];
}
// terminating the s1 string
s1[i] = '\0';

printf("After concatenation: \n");


puts(s1);

return 0;
}

OUTPUT:---

Enter the First String:Hello RCE Students......


Enter the Second String:WELCOME
After concatenation:
Hello RCE Students......
WELCOME
//Finding the length of string without strlen()

#include <stdio.h>
int main()
{
char s[50] ;
int length; OUTPUT:--

Enter the String:Fun Programming


printf("\n Enter the String:");
Length of the String is:15
fgets(s,sizeof(s),stdin);

// Finding the length of the String


for(length=0;s[length]!='\0';++length);

printf("\n Length of the String is:%d",--length);


return 0;
}
Array of Strings
• In C programming String is a 1-D array of characters
and is defined as an array of characters.
• But an array of strings in C is a two-dimensional array
of character types.
• Each String is terminated with a null character (\0). It
is an application of a 2d array.

Syntax:

char variable_name[size1][size2]= {list of string};


char ch_arr[3][10] = {
{'s', 'p', 'i', 'k', 'e', '\0'},
{'t', 'o', 'm','\0'},
{'j', 'e', 'r', 'r', 'y','\0'}
};

C provides an alternative syntax for the above initialization which is


shown below:

char ch_arr[3][10] = {
"spike",
"tom",
"jerry"
};
• The first subscript of the array i.e 3 denotes the
number of strings in the array and the second
subscript denotes the maximum length of the
string.
• Each character occupies 1 byte of data, so when
the compiler sees the above statement it
allocates 30 bytes (3*10) of memory.

A + 0 points to the 0th string, A + 1 points to the


1st string and A + 2 points to the 2nd string.
the name of an array is a pointer to the 0th element of
the array

Therefore, if ch_arr points to address 1000 then ch_arr + 1


will point to address 1010.
ch_arr + 0 points to the 0th string or 0th 1-D array.
ch_arr + 1 points to the 1st string or 1st 1-D array.
ch_arr + 2 points to the 2nd string or 2nd 1-D array.
*(A + 0) + 0 points to the 0th character of 0th 1-D array (= s)
*(A + 0) + 1 points to the 1st character of 0th 1-D array (= p)
*(A + 1) + 2 points to the 2nd character of 1st 1-D array (= m)

To get the element at jth position of i th 1-D array, just


dereference the whole expression as
*(A + i) + j or A[i][j].
// Program demonstrates how to print an array of strings.
#include<stdio.h>
int main()
{
int i;
char A[3][10] = {
"spike",
"tom",
"jerry"
};

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


{
printf("string = %s \n", A + i);
}
return 0;
}

You might also like