0% found this document useful (0 votes)
13 views25 pages

UNIT-1 String K

The document provides a comprehensive overview of strings in C, including their definition, declaration, initialization, and manipulation functions. It covers string input/output, common string functions like strlen, strcmp, strcat, and strcpy, as well as the handling of character arrays. Additionally, it highlights the importance of the null character in string termination and the limitations of functions like scanf for multi-word strings.

Uploaded by

Nivya babu
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)
13 views25 pages

UNIT-1 String K

The document provides a comprehensive overview of strings in C, including their definition, declaration, initialization, and manipulation functions. It covers string input/output, common string functions like strlen, strcmp, strcat, and strcpy, as well as the handling of character arrays. Additionally, it highlights the importance of the null character in string termination and the limitations of functions like scanf for multi-word strings.

Uploaded by

Nivya babu
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/ 25

Strings

• String in C
• Intorduction ,Declaration,Initialization,
• String I/O ,Array of string
• String Manupulation Function :-
• String Length,Copy,Compare Concatenate
search for sub string

Arrays
Strings
▪ A string is a series of characters treated as a single unit.
▪ A string may include letters, digits and various special characters
such as +,-,*,/ and $.
▪ String literals or string constants are written in double quotation
marks.
For example : - “LOTUS” “DH0019” “12345” “Welcome to Malaysia”
▪ A string in C is an Array of characters ending with the “null”
character(‘\0’).
▪ C has no type “String”
▪ A string constant is a list of characters enclosed in double quotes.
For example,
char str1[ 12]=“hello there”;
▪ Character arrays also can be initialized with individual character
constants in an initializer list.
For example,
char s1[ ]={‘f’,’i’,’r’,’s’,’t’,’\0’};
Arrays Slide 6 (of 38)
Declaration of string

Declaring a string is as simple as declaring a one-dimensional array. Below is


the basic syntax for declaring a string.
char str_name[size];
In the above syntax str_name is any name given to the string variable and size
is used to define the length of the string, i.e the number of characters strings
will store.
Note: There is an extra terminating character which is the Null character (‘\0’)
used to indicate the termination of a string that differs strings from normal
character arrays.

Arrays
Initializing a String
A string can be initialized in different ways. We will explain this with the help
of an example..

4 Ways to Initialize a String in C

1. Assigning a string literal without size: String literals can be assigned


without size. Here, the name of the string str acts as a pointer because it is
an array.

char str[] = "I Like Programming";


2. Assigning a string literal with a predefined size: String literals can be
assigned with a predefined size. But we should always account for one extra
space which will be assigned to the null character. If we want to store a string
of size n then we should always declare a string with a size equal to or
greater than n+1.
char str[50] = "I Like Programming";

Arrays
3. Assigning character by character with size: We can also assign a
string character by character. But we should remember to set the end
character as ‘\0’ which is a null character.
char str[14] = { 'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};
4. Assigning character by character without size: We can assign
character by character without size with the NULL character at the end.
The size of the string is determined by the compiler automatically.
char str[] = { 'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};
Below is the memory representation of the string “Geeks”.

Arrays
Strings I/O
For example,
char color[ ]=“White”;
or.
char color[5];
scanf(“%s”,color);
printf(“%s”,color);
“%s” is a control string for the strings.

Arrays Slide 8 (of 38)


Strings

While entering the string using scanf( ) we must be cautious


about two things:
• The & (address operator) is normally used to provide scanf with a
variable’s location in memory so a value can be stored.
• An array name is the address of the start of the array; therefore,the &
is not necessary, and is incorrect.
• The length of the string should not exceed the dimension of the
character array. This is because the C compiler doesn’t perform
bounds checking on character arrays. Hence, if you carelessly exceed
the bounds there is always a danger of overwriting something
important
• scanf( ) is not capable of receiving multi-word strings. Therefore
names such as ‘Debashish Roy’ would be unacceptable. The way to
get around this limitation is by using the function gets( ).

Arrays Slide 8 (of 38)


Strings
main( )
{
char name[25] ;
printf ( "Enter your full name " ) ;
gets ( name ) ;
puts ( "Hello!" ) ;
puts ( name ) ;
}
And here is the output...
Enter your name Debashish Roy
Hello!
Debashish Roy

Arrays Slide 8 (of 38)


Strings

• puts( ) can display only one string at a time (hence the


use of two puts( ) in the program above)
• Also, on displaying a string, unlike printf( ), puts( ) places
the cursor on the next line.
• Though gets( ) is capable of receiving only one string at a
time, the plus point with gets( ) is that it can receive a
multi-word string

Arrays Slide 8 (of 38)


Character Arrays 1/3

/*Using character arrays as strings*/


main()
{ char s1[20],s2[20]=“experience”;
int i;
printf(“\nEnter a string :”);
scanf(“%s”,s1);

Arrays
Character Arrays 2/3
printf(“String 1 is:“);
for(i=0; s1[i] !=‘\0’;i++)
printf(“%c”,s1[i]);
printf(“\n”);
printf(“String 1 with spaces between characters:\n“);
for(i=0;s1[i] !=‘\0’;i++)
This is how you tell if
printf(“%c ”,s1[i]); you are at the end of
printf(“\n”); the string.

Enter a String : Hi there!


String 1 is:Hi there!
String 1 with spaces between characters:
Hi there!
Arrays
Character Arrays 3/3

printf(“String 2 is:”);
for(i=0;s2[i] !=‘\0’;i++)
printf(“%c”,s2[i]);
printf(“\n”);
}

String 2 is: experience

Arrays
Standard Library String Functions

Arrays Slide 8 (of 38)


Standard Library String Functions

strlen( )
• This function counts the number of characters present
in a string.
main( )
{
char arr[ ] = "Bamboozled" ;
int len1, len2 ;
len1 = strlen ( arr ) ;
len2 = strlen ( "Humpty Dumpty" ) ;
printf ( "\nstring = %s length = %d", arr, len1 ) ;
printf ( "\nstring = %s length = %d", "Humpty Dumpty", len2
);
}
Arrays Slide 8 (of 38)
Standard Library String Functions
The output would be...
string = Bamboozled length = 10
string = Humpty Dumpty length = 13
• Note that in the f irst call to the function strlen( ), the
base address of the string is passed , and the function in
turn returns the length of the string.
While calculating the length it doesn’t count ‘\0’.
Even in the second call, len2 = strlen ( "Humpty Dumpty" ) ;
what gets passed to strlen( ) is the address of the string
and not the string itself

Arrays Slide 8 (of 38)


strcmp() function :
strcmp() function is used to compare two strings.
strcmp() function does a case sensitive comparison
between two strings. The two strings are compared
character by character until there is a mismatch or end
of one of the strings is reached . If the two strings are
identical, strcmp( ) returns a value zero. If they‟re not, it
returns the numeric difference between the ASCII values
of the first non-matching pairs of characters.

Syntax strcmp(StringVariable1, StringVariable2);

Arrays
#include <stdio.h>
#include <string.h>
int main(void)
{
//variable
char str1[100], str2[100];
//input
printf("Enter string 1: ");
gets(str1);
printf("Enter string 2: ");
gets(str2);
if (strcmp(str1, str2) == 0) {
printf("Both are same.\n");
}
else {
printf("Both are different.\n");
}
printf("End of code\n");
return 0;

}
Arrays
strcat() function
The strcat() is used to concatenate two strings. The second
string will be appended to the end of the first string. This
process is called concatenation.
Syntax strcat (StringVariable1, StringVariable 2);

Arrays
#include <stdio.h>
#include <string.h>
int main(void)
{
//variable
char
str1[] = "Hello",
str2[] = "World",
str3[100] = "";

//concat
strcat(str3, str1); //concat "Hello" to str3 so, str3 = "Hello"
strcat(str3, " "); //concat " " to str3 so, str3 = "Hello "
strcat(str3, str2); //concat "World" to str3 so, str3 = "Hello World"

printf("Concatenated string: %s\n", str3);

printf("End of code\n");
return 0;

Arrays
strcpy (Destination string,source string):

This function accepts 2 strings as


parameter,1st one is destination string and
2nd is source string. This function copies
source string to destination string.

Arrays
#include <stdio.h>
#include <string.h>
int main(void)
{
//variable
char
str1[] = "Hello",
str2[] = "World",

strcpy(str2, str1); //concat "Hello" to str3 so, str3 = "Hello"

printf(" string1 %s\n", str1);


printf(" string2 %s\n", str2);

return 0;

Arrays
Sub String

Arrays
#include <string.h>
#include <stdio.h>

int main()
{
// Take any two strings
char s1[] = "GeeksforGeeks";
char s2[] = "for";
char* p;
// Find first occurrence of s2 in s1
p = strstr(s1, s2);

Arrays
// Prints the result
if (p) {
printf("String found\n");
printf("First occurrence of string '%s' in '%s'
is '%s'", s2, s1, p);
} else
printf("String not found\n");

return 0;
}

Arrays

You might also like