Strings in C

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 40

Strings

1
C Strings
In C language a string is group of characters (or) array of characters, which is terminated by

delimiter \0 (null). Thus, C uses variable-length delimited strings in programs.


Declaring Strings:-

C does not support string as a data type. It allows us to represent strings as character arrays. In
C, a string variable is any valid C variable name and is always declared as an array of characters.

Syntax:- char string_name[size];

The size determines the number of characters in the string name.

Ex:- char city[10];


char name[30];
2
Initializing strings:-
• There are several methods to initialize values for
string variables.
• Initializing location character by character
• Partial array initialization
• Initialization without specifying the size
• Array initialization with a string

3
Initializing location character by character
• Consider the following declaration With initialization:
char b[9]= { ‘C’, ‘O’,’M’,’P’,’U’,’T’,’E’,’R’};

C O M P U T E R \0

0 1 2 3 4 5 6 7 8

4
Partial array initialization
• Consider the following declaration With initialization:
char a[10]= {‘R’,’A’,’M’,’A’};

R A M A \ \ \ \ \0 \0
0 0 0 0
0 1 2 3 4 5 6 7 8 9

5
Initialization without specifying the size
• Consider the following declaration With initialization:
char a[]= {‘D’,’S’,’A’,’T’,’M’};

D S A T M

0 1 2 3 4

Note that ‘\0’ is not inserted at the end of the string.

6
Array initialization with a string
• Consider the following declaration With string initialization:
char b[]=“COMPUTER”;

C O M P U T E R \0

0 1 2 3 4 5 6 7 8

7
Storing strings in memory:-
• In C a string is stored in an array of characters and terminated by \0
(null).

• A string is stored in array, the name of the string is a pointer to the


beginning of the string. The character requires only one memory
location.
• If we use one-character string it requires two locations. The difference
is shown below,

8
• Because strings are variable-length structure, we must provide
enough room for maximum- length string to store and one byte for
delimiter.

Ex: char str[20]; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19


W E L C O M E T O D S A T M \0

String Array
Why do we need null?
• A string is not a datatype but a data structure. String implementation
is logical not physical. The physical structure is array in which the
string is stored. The string is variable-length, so we need to identify
logical end of data in that physical structure.
9
String constant (or) Literal:-

String constant is a sequence of characters enclosed in double quotes.


When string constants are used in C program, it automatically initializes
a null at end of string.

Ex:- “Hello” “Welcome” “Welcome to C Lab”

10
STRING I/O FUNCTIONS

11
FORMATTED I / O FUNCTIONS

Formatted Input Function:


The input function scanf ( ) is used to read the string. The
conversion code used is %S to read a string of characters.
Example: char addr[15];
scanf (“%s”, addr);
The “&” operator should not be used to read the string variables.
Formatted Output Function:
The output function printf( ) is used to display/print the string.
The conversion code/ format specifier used is %s to print the
string of characters.
Example: char a[10]; scanf (“%s”, a);
printf (“%s”, a);
Prints the characters ie., group of characters on to the monitor.
12
Reading strings from terminal
formatted input function:- scanf can be used with %s format specification to read
a string.

Ex:- char name[10];


scanf(“%s”,name);

Here don't use “&‟ because name of string is a pointer to array. The problem with
scanf is that it terminates its input on the first white space it finds.
Ex:- NEW YORK

Reads only NEW (from above example).

13
Writing strings on to the screen:-
Using formatted output functions:- printf with %s format specifier we
can print strings in different formats on to screen.
Ex:- char name[10];
printf(“%s”,name);

14
UNFORMATTED I / O
gets( ): (unformatted input function)
To read sequence of characters from keyboard with spaces in between and store them in memory
locations. gets( ) function is used.
Syntax:
gets(str);
str - string variable

Reads string of characters from keyboard till users presses “Enter key”.

Puts( ): (unformatted output function)


To display the string of characters. On the output screen puts ( ) function is used.
Syntax:
puts (str);
str-string variable
The function displays all the characters stored in variable “str” till it encounters NULL character `\0'.
15
EXAMPLE PROGRAM
Example:
#include <stdio.h>
#include <string.h>
void main ( )
{
char str[25];
gets (str); //Input ABC (Press Enter)
puts (str); //Output ABC
}
16
STRING MANIPULATION FUNCTIONS

• strlen (str) - returns the length of string str.


• strcpy (dest,src) - copies the source string src to destination string dest.
• strncpy (dest,src,n) - copies at most n characters of source string src to
destination string dest.
• strcat (str1, str2) - append string str2 to str1.
• strncat (str1, str2,n) - append first n characters of string str2 to str1.
• strcmp (str1, str2) - compare two strings str1 & str2.
• strlwr (str) - converts the string str to lower case
• strupr (str) - converts the string str to upper case
• strrev (str) - reverses the string str

17
strlen (str): string length
The function returns the length of the string str, it counts all the characters until ‘\0’ and returns the
total length.
Syntax:
int strlen (char str[ ]);
Example:
#include <stdio.h>
#include <string.h>
void main ( )
{
char s[ ] = “LAKSHMANA”;
printf (“length = %d”, strlen (s));
}
Output:
length = 9.
18
strcpy (dest,src) - String Copy
The function strcpy copies the contents of source string src to destination string dest
including ‘\0’. Here the size of destination string should be greater or equal to the source
string.
Syntax:
strcpy (char dest[ ], char src[ ]);

#include <stdio.h>
#include <string.h>
void main ( )
{
char src[ ] = “PROGRAM”;
char dest[10];
strcpy (dest, src);
printf (“Destination = %s”, dest);
19
}
strncpy (dest,src,n) - String Copy
The function strncpy copies ‘n’ number of characters of source string src to destination
string dest. Here the size of destination string should be greater or equal to the source
string.
Syntax:
strncpy (char dest[ ], char src[ ],int n);

#include <stdio.h>
#include <string.h>
void main ( )
{
char src[ ] = “PROGRAM”;
char dest[10];
strcpy (dest, src,4);
printf (“Destination = %s”, dest);
20
}
strcat (str1, str2) - append string str2 to str1.
This function is used to concatenate two strings. i.e., it appends one string at
the end of the specified string. Its syntax as follows:
strcat(string1,string2);
where string1 and string2 are one-dimensional character arrays.

This function joins two strings together. In other words, it adds the string2 to
string1 and the string1 contains the final concatenated string.
E.g., string1 contains prog and string2 contains ram, then string1 holds
program after execution of the strcat() function
Example:
char str1[10 ] = “VERY”;
char str2[ 5] =”GOOD”;
strcat(str1,str2); 21
A program to concatenate one string with another
using strcat() function
#include<stdio.h>
#include<string.h>
int main()
{
char s1[30],s2[15];
printf(“\n Enter first string:”);
gets(s1);
printf(“\n Enter second string:”);
gets(s2);
if(sizeof(s1)>=strlen(s1)+srtlen(s2))
{
strcat(string1,string2);
printf(“\n Concatenated string=%s”,string1);
}
else
printf(“Concatenation not possible\n) 22
}
strcmp() compare two strings str1 & str2.
The strcmp() function compares two strings and returns 0 if both strings are identical
Present in string.h library

Syntax:
int strcmp (const char* str1, const char* str2);

• The strcmp() function takes two strings and returns an integer.


• The strcmp() compares two strings character by character.
• If the first character of two strings is equal, the next character of two
strings are compared. This continues until the corresponding
characters of two strings are different or a null character '\0' is
reached.

23
Return Value from strcmp()
ASCII
A=65 a=97
B=66 b=98
Return Value Remarks
C=67 c=99
if both strings are identical .
0 .
(equal)
.
if the ASCII value of the first .
negative unmatched character is less
than second.

if the ASCII value of the first


positive integer unmatched character is greater
than second.

24
ASCII
Example: C strcmp() function A=65 a=97
B=66 b=98
C=67 c=99
#include <stdio.h>
str1 str2 str3
#include <string.h>
a a a
int main() str1[0] str2[0] str3[0]
{ char str1[] = "abcd", str2[] = "abCd", str3[] = "abcd"; b b
str1[1] str2[1] b str3[1]
int result1,result2;
c c
str1[2] str2[2] C str3[2]
// comparing strings str1 and str2
result1 = strcmp(str1, str2); d d d
str1[3] str2[3] str3[3]
printf("strcmp(str1, str2) = %d\n", result1);
\0 \0 \0
str1[4] str2[4] str3[4]
// comparing strings str1 and str3
result2 = strcmp(str1, str3);
printf("strcmp(str1, str3) = %d\n", result2); result1=str1[2]-srt2[2] result2=str1[4]-srt3[4]
=99-67 =\0 - \0
}
=32 =0-0
=0
25
• Output
ASCII
strcmp(str1, str2) = 32 A=65 a=97
B=66 b=98
strcmp(str1, str3) = 0 C=67 c=99

26
Array of strings

27
Array of strings
We have array of integers, array of floating point numbers, etc.. similarly we
have array of strings also.
Collection of strings is represented using array of strings.

Declaration:-
char arr[row][col];

where,
arr - name of the array
row - represents number of strings
col - represents size of each string
28
Initialization:-
char arr[row][col] = {list of strings };

Example:-
0 1 2 3 4 5 6 7 8 9
char city[5][10] = { “DELHI”,
0 D E L H I \0
“CHENNAI”,
“BANGALORE”, 1 C H E N N A I \0
“HYDERABAD”,
2 B A N G A L O R E \0
“MUMBAI” };
3 H Y D E R A B A D \0
4 M U M B A I \0

In the above storage representation memory is wasted due to the fixed length
for all strings.
29
Write a C program to print array of strings:
include <stdio.h>

int main()
{

int i;
char city[5][10] = { "DELHI",
"CHENNAI",
"BANGALORE",
"HYDERABAD",
"MUMBAI" };

printf("strings are:\n");
for(i=0;i<=5;i++)
{
printf("%s\n", city[i]);
}

}
30
Write a C program to read and print array of strings.
#include <stdio.h>
int main()
{ 0 1 2 3 4 5 6 7 8 9. . .
int i,n;
char city[10][20]; 0
printf("Enter the number of string:\n");
scanf("%d", &n); 1

printf("enter the strings:\n"); 2


for(i=0;i<n; i++)
{
3
scanf("%s", city[i]);
}
4
printf("\n strings are:\n");
for(i=0;i<n;i++)
{
printf("%s\n", city[i]);
}
}

31
OUTPUT:
Enter the number of string:
5
enter the strings:
DSATM
DSCE
DSI
DSBA
DSU

strings are:
DSATM
DSCE
DSI
DSBA
DSU

32
Write functions to implement string operations such as compare, concatenate, string length.

#include <stdio.h> int length1 = string_length(s1);


int compare_strings(char [], char []); int length2 = string_length(s2);
void concatenate(char [], char []); printf("Length of %s = %d\n", s1, length1);
int string_length(char []); printf("Length of %s = %d\n", s2, length2);

int main() if (compare_strings(s1, s2) == 0)


{ printf("Equal strings.\n");
char s1[100], s2[100]; else
printf("Unequal strings.\n");
printf("Input a string1\n");
gets(s1);
concatenate(s1, s2);
printf("Input a string2\n");
printf("String obtained on concatenation: %s \n", s1);
gets(s2);

}
int string_length(char s1[]) int compare_strings(char s1[], char s2[])
void concatenate(char s1[], char s2[])
{ {
{
int i = 0; int i, j;
int i = 0;
while (s1[i] == s2[i]) i = 0;
while (s1[i] != '\0') { while (s1[i] != '\0')
i++; if (s1[i] == '\0' || s2[i] == '\0') {
break;
return i; i++;
i++;
} }
}
if (s1[i] == '\0' && s2[i] == '\0') j = 0;
return 0; while (s2[j] != '\0')
else {
return 1; s1[i] = s2[j];
} j++;
i++;
}
s1[i] = '\0';
}
OUTPUT:
Input string1
dsatm
Input string2
dsi
Length of string1: 5
Length of string2: 3
Unequal string
String obtained on concatenation: dstamdsi
Write a C program that reads a sentence and
prints the frequency of each of the vowels
and total count of consonants

36
#include <stdio.h>

void main()
{ 0 1 2 3 4 5 6 7 8 9
char str[80]; 10 11 12 13 14 15 16
int i, vowels = 0, consonants = 0;
W E L C O M E T O D S A T M \0
printf("Enter a str \n");
gets(str);

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


{
if(isalpha(str[i]))
{
ch=tolower(str[i])
if (ch == 'a' || ch== 'e' || ch== 'i' || ch== 'o' || ch== 'u')
{
vowels = vowels + 1;
}
else
{
consonants = consonants + 1;
}
}

printf("No. of vowels = %d\n", vowels);


printf("No. of consonants= %d\n", consonants); 37
}
Output:
Enter a string
welcome to dsatm
No. of vowels = 5
No. of consonants= 9

38
To print frequency of each vowel and total
count of consonants in a sentence

39
#include<stdio.h>
void main()
{
char s[100];
printf("\nIn the sentence \"%s\" :",s);
int j, ac=0, ec=0, ic=0, oc=0, uc=0, cc=0;
printf("Enter a sentence\n");
gets(s); printf("\nThe frequency vowel of A/a is %d",ac);
for(j=0;s[j]!='\0';j++)
{ printf("\nThe frequency vowel of E/e is %d",ec);
if(isalpha(s[j]))
{ printf("\nThe frequency vowel of I/i is %d",ic);
if(s[j]=='A'||s[j]=='a')
ac++;
printf("\nThe frequency vowel of O/o is %d",oc);
else if(s[j]=='E'||s[j]=='e’)
ec++; printf("\nThe frequency vowel of U/u is %d",uc);
else if(s[j]=='I'||s[j]=='i’)
ic++; printf("\nThe total count of all consonents is %d",cc);
else if(s[j]=='O'||s[j]=='o’)
oc++; }
else if(s[j]=='U'||s[j]=='u’)
uc++;
else if(s[j]!=' ‘)
cc++;
}
}
40

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy