UNIT-3 Strings
UNIT-3 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:
• By char array
• By string literal
• By char array
char c[] = {'a', 'b', 'c', 'd', '\0'};
• By string literal
scanf("%s", name);
#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:
return 0;
}
strcpy()
This function copies contents of one string into another
string.
strcpy( str1, str2) – It copies contents of str2 into str1.
strcpy(copy_str,string1);
strcat(string1,string2);
Syntax : strcmp(string1,string2);
#include <stdio.h>
#include <string.h>
int main()
{
char string1[20], string2[20] ;
Syntax:
strlwr(string);
Example :
char str[ ] = “MODIFY “;
printf(“%s\n”, strlwr (str));
Output :
modify
strupr():
Syntax :
strupr(string);
Example :
char str[ ] = “modify “;
printf(“%s\n”, strupr(str));
Output :
MODIFY
strrev():
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
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;
// concatenate s2 to s1
for (j = 0; s2[j] != '\0'; ++j, ++i) {
s1[i] = s2[j];
}
// terminating the s1 string
s1[i] = '\0';
return 0;
}
OUTPUT:---
#include <stdio.h>
int main()
{
char s[50] ;
int length; OUTPUT:--
Syntax:
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.