0% found this document useful (0 votes)
39 views13 pages

LectureMaterial 1

Uploaded by

devaki meena
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)
39 views13 pages

LectureMaterial 1

Uploaded by

devaki meena
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/ 13

STRINGS

A String in C programming is a sequence of characters terminated with a


null character ‘\0’. The C String is stored as an array of characters. The
difference between a character array and a C string is that the string in C is terminated
with a unique character ‘\0’.

C String Declaration Syntax

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


Below is the basic syntax for declaring a string.
char string_name[size];

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.

C String Initialization

Strings in C language can be initialized by 4 ways


Example 1:
// C program to illustrate strings

#include <stdio.h>

#include<stdio.h>

#include <string.h>

int main()

{ char str[] = "Geeks";

printf("%s\n", str);

int length = 0;

length = strlen(str);

printf("Length of string str is %d\n", length);

printf("Size of string is %d",sizeof(str));

return 0;

}
Output:
Geeks
Length of string str is 5
Size of string is 6
Example 2:
Read a String Input From the User
#include<stdio.h>
int main()
{
// declaring string
char str[50];

// reading string
scanf("%s", str);

// print string
printf("%s",str);

return 0;
}

Input
GeeksforGeeks
Output
GeeksforGeeks

We can see in the above program that the string can also be read using a single scanf
statement. Also, we might be thinking that why we have not used the ‘&’ sign with the
string name ‘str’ in scanf statement!

We know that the ‘&’ sign is used to provide the address of the variable to the scanf()
function to store the value read in memory. As str[] is a character array so using str
without braces ‘[‘ and ‘]’ will give the base address of this string. That’s why we have
not used ‘&’ in this case as we are already providing the base address of the string to
scanf.
Example 3:
// C Program to take input string which is separated by whitespaces
#include <stdio.h>
int main()
{
char str[20];
scanf("%s", str);
printf("%s", str);
return 0;
}

Input
Geeks for Geeks
Output
Geeks
Here, the string is read only till the whitespace is encountered.

How to Read a String Separated by Whitespaces in C?


We can use multiple methods to read a string separated by spaces in C. The two of the
common ones are:
1. We can use the fgets() function to read a line of string and gets() to read
characters from the standard input (stdin) and store them as a C string
until a newline character or the End-of-file (EOF) is reached.
2. We can also scanset characters inside the scanf() function

Example 4:
// C program to illustrate fgets()
#include <stdio.h>
#define MAX 50
int main()
{
char str[MAX];

// MAX Size if 50 defined


fgets(str, MAX, stdin);

printf("String is: \n");

// Displaying Strings using Puts


puts(str);

return 0;
}

Input
Geeks for Geeks
Output
String is:
Geeks for Geeks

Example 5:
// C Program to take string separated by whitespace using scanset characters
#include <stdio.h>
int main()
{
char str[20];
// using scanset in scanf
scanf("%[^\n]s", str);
// printing read string
printf("%s", str);

return 0;
}

Input
Geeks for Geeks
Output
Geeks for Geeks
String Handling Functions:
strcpy() strcpy(string1, string2) Copies string2 value into string1

strncpy() strncpy(string1,string2,5) Copies first 5 characters string2 into


string1
strlen() strlen(string1) returns total number of characters in
string1
strcat() strcat(string1,string2) Appends string2 to string1
strncat() strncat(string1,string2,4) Appends first 4 characters of string2 to
string1
strcmp() strcmp(string1, string2) Returns 0 if string1 and string2 are the
same; less than 0 if string1<string2; greater
than 0 if string1>string2
strncmp() strncmp(string1,string2,4) Compares first 4 characters of bothstring1 and
string2

strcmpi() strcmpi(string1,string2) Compares two strings, string1 and string2


by ignoring case (upper or lower)

stricmp() stricmp(string1,string2) Compares two strings, string1 and string2


by ignoring case (similar to strcmpi())

strlwr() strlwr(string1) Converts all the characters of string1 to


lower case.

strupr() strupr(string1) Converts all the characters of string1 to


upper case.
strdup() string1 = strdup(string2) Duplicated value of string2 is assigned to
string1
strchr() strchr(string1, 'b') Returns a pointer to the first occurrence of
character 'b' in string1

strrchr() 'strrchr(string1, 'b') Returns a pointer to the last occurrence of


character 'b' in string1

strstr() strstr(string1, string2) Returns a pointer to the first occurrence of


string2 in string1

strset() strset(string1, 'B') Sets all the characters of string1 to given


character 'B'.

Strlen()
The strlen() function calculates the length of a given string.
The strlen() function takes a string as an argument and returns its length. The
returned value is of type size_t (an unsigned integer type).
Example
#include
<stdio.h>
#include
<string.h> int
main()
{
char a[20]="Program";
char b[20]={'P','r','o','g','r','a','m','\0'}; // using the %zu format specifier to
print size_t
printf("Length of string a = %zu \n",strlen(a));
printf("Length of string b = %zu
\n",strlen(b)); return 0;
}

Output
Length of string a = 7
Length of string b = 7
Note: strlen() function doesn't count the null character \0 while calculating the length

Strcpy()
The strcpy() function copies the string pointed by source (including the null character)
to the destination. The strcpy() function also returns the copied string.

The syntax is
char* strcpy(char* destination, const char* source);

Example
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "C programming";
char str2[20]; // copying str1 to str2
strcpy(str2, str1);
puts(str2); // C programming
return 0;
}

Output

C programming

Note: In strcpy(), the size of the destination string should be large enough to store the
copied string. Otherwise, it may result in undefined behavior.

Strcmp()
The strcmp() compares two strings character by character. If the strings
are equal, the function returns 0.

The syntax of strcmp() is:


int strcmp (const char* str1, const char* str2);
Example:
#include <stdio.h>
#include <string.h>
int main()
{
char str1[] = "abcd", str2[] = "abCd", str3[] = "abcd";
int result; // comparing strings str1 and str2
result = strcmp(str1, str2);
printf("strcmp(str1, str2) = %d\n", result);
// comparing strings str1 and str3
result = strcmp(str1, str3);
printf("strcmp(str1, str3) = %d\n", result);
return 0;
}

Output
strcmp(str1, str2) = 1
strcmp(str1, str3) = 0

Strcat()
In C programming, the strcat() function concatenates (joins) two strings.
The function definition of strcat() is:
char *strcat(char *destination, const char *source)

Example
#include <stdio.h>
#include <string.h>
int main() {
char str1[100] = "This is ",
str2[] = "programiz.com";
// concatenates str1 and str2 the resultant string is stored in str1.
strcat(str1, str2);
puts(str1);
puts(str2);
return 0;
}

Output
This is programiz.com
programiz.com

Note:
The strcat() function concatenates the destination string and the source
string, and the result is stored in the destination string.
The size of the destination string should be large enough to store the
resultant string. If not, we will get the segmentation fault error.

Two-dimensional array of strings

Syntax:-
char string-array-name[row-size][column-size];

Here the first index (row-size) specifies the maximum


number of strings in the array, and the second index
(column-size) specifies the maximum length of every
individual string.

An example of two dimensional characters or the array of Strings is,

char language[5][10] = {"Java", "Python", "C++", "HTML", "SQL"};

Here, char language[5][10]; In the “language” array we can store a


maximum of 5 Strings and each String can have a maximum of 10
characters.
In C language, each character takes 1 byte of memory. For the
“language” array it will allocate 50 bytes (1*5*10) of memory. Where
each String will have 10 bytes (1*10) of memory space.

Initialization of array of strings


Two dimensional (2D) strings in C language can be directly initialized
as shown below,

char language[5][10] =
{"Java", "Python", "C++", "HTML", "SQL"};

char largestcity[6][15] =
{"Tokyo", "Delhi", "Shanghai", "Mumbai", "Beijing", "Dhaka"};

The two dimensional (2D) array of Strings in C also can be initialized


as,

char language[5][10] =
{
{'J','a','v','a','\0'},
{'P','y','t','h','o','n','\0'},
{'C','+','+','\0'},
{'H','T','M','L','\0'},
{'S','Q','L','\0'}
};

Since it is a two-dimension of characters, so each String (1-D array of


characters) must end with null character i.e. ‘\0’

Each String in this array can be accessed by using its index number.
The index of the array always starts with 0.
language[0] => "Java";
language[1] => "Python";
language[2] => "C++";
language[3] => "HTML";
language[4] => "SQL";

Note:- the number of characters (column-size) must be declared at


the time of the initialization of the two-dimensional array of strings.

// it is valid
char language[ ][10] = {"Java", "Python", "C++", "HTML", "SQL"};

But that the following declarations are invalid.


// invalid
char language[ ][ ] = {"Java", "Python", "C++", "HTML", "SQL"};

// invalid
char language[5][ ] = {"Java", "Python", "C++", "HTML", "SQL"};

Note:- Once we initialize the array of String then we can’t directly


assign a new String.

char language[5][10] = {"Java", "Python", "C++", "HTML", "SQL"};

// now, we can't directly assign a new String


language[0] = "Kotlin"; // invalid

// we must copy the String


strcpy(language[0], "Kotlin"); // valid
// Or,
scanf(language[0], "Kotlin"); // valid

Reading and displaying 2d array of strings in C


The two-dimensional array of strings can be read by using loops. To
read we can use scanf(), gets(), fgets().

// reading strings using for loop


for(i=0;i<n;i++)
{
scanf("%s[^\n]",name[i]);
}

Or,

// reading strings using while loop


int i=0;
while(i<n)
{
scanf("%s[^\n]",name[i]);
i++;
}

The two-dimensional array of strings can be displayed by


using loops. To display we can use printf(), puts(), fputs().

// displaying strings using for loop


for(i=0;i<n;i++)
{
puts(name[i]);
}

Or,

// displaying strings using while loop


int i=0;
while (i<n)
{
puts(name[i]);
i++;
}

Sample program to read the 2D array of characters or


array of String in C

#include<stdio.h>
int main()
{
// declaring and initializing 2D String
char language[5][10] = {"Java", "Python", "C++", "HTML",
"SQL"};

// Dispaying strings
printf("Languages are:\n");
for(int i=0;i<5;i++)
puts(language[i]);
return 0;
}

Output:-

Languages are:
Java
Python
C++
HTML
SQL

You might also like