Sunteți pe pagina 1din 47

STRINGS

Introduction
● In C a string is represented as some characters enclosed by
double quotes.
“ This is a string”

● A string may contain any character, including special


control characters, such as ‘\n’, ‘\r’, ‘\7’ etc...

“ Day is Good\n”
Definition
● Array of character are called strings.A string can be defined as
sequence of character.
● A string is terminated by null character \0.
For ex: “c strings “
● The above string can be pictorially represented as shown below:

c s t r i n g s \0

● There is no separate data type for strings in C. They are treated as


arrays of type ‘char’.

● So, a variable which is used to store an array of characters is called a


string variable.
Declaration of String
● Strings are declared in C in similar manner as arrays. Only
difference is that, strings are of ‘char’ type.
● For ex:
char s[5]; //string variable name can hold maximum of 5
characters excluding NULL character
• The above code can be pictorially represented as shown
below:

s[0] s[1] s[2] s[3] s[4] s[5]


\0
Initialization of String
● The string can be initialized at comiple time as:
1. char s[9]={‘M', 'a', 'n', 'g' ,’a’,’l’,’o’,’r’,’e’};
2. char s[9]="Mangalore";
• The above code can be pictorially represented as shown below:

M a n g a l o r e \0
Reading and printing string
Using scanf and printf functions:
#include<stdio.h>
void main()
{ Output:
char str[10]; enter a string:
printf(“enter a string: \n”); NITK Mangalore
scanf(“%s”, str); string is: NITK
printf(“string is %s:”, str);
}
● The problem with the scanf function is that it terminates its input on
the first white space if finds.
● A white space include blank,tabs,new line etc…
● In the case of character array, ‘&’ is not required before the variable
name in scanf().
● We can also specify field width using the form %ws in the scanf
statement for reading a specified number of character from the input
string.For example: char name[10]; //name=“krishna”
scanf(“%5s”,name);
The input string is stored as:
K R I S H \0 ? ? ? ?
Using gets() and puts() functions
The advantage of using gets function is that, it can read a string
containing whitespace characters but gets can only read one string at a
time.
#include <stdio.h>
int main(){ Output:
char inputString[100]; Enter a string
C programming
printf("Enter a string\n"); Course
gets(inputString); C programming
Course
puts(inputString);
}
Formatting the string :
Consider char a[10]=“WELCOME”;
Example 1: printf(“%s”, a);

W E L C O M E

Example 2: printf(“%10s”,a);
W E L C O M E

Example 3:printf(“%d %10s”,5,a);

5 W E L C O M E
Example 4: printf(“%d %10.2s”,5,a);

5 W E

Example 5: printf(“%d %-10.2s”,5,a);

5 W E
Reading line of text using scanf()
● scanf() cannot be used for reading a text containing more than one
word.
● C supports format specification know as the edit set conversion
code %[..] that can be used to read line of variety of characters,
include whitespaces.
● For example:
#include<stdio.h>
main()
{
char line[10];
scanf(“%[^\n]s”, line);
printf(“%s”, line);
}
Here, %[^\n]s will read all characters until you reach  \n and put them in s.
Example 2:
scanf("%[^0-9]s",ch);
printf("%s",ch);

Input 1: welcome18 nitk Input 2: 18welcome nitk


Output 1:welcome Output 2:

Example 3:
scanf("%[0-9]s", ch);
printf("%s",ch);

Input 1: 2018welcome nitk Input 2: welcome2018 nitk


Output 1:2018 Output 2:
Example 4:
scanf("%[^a-z]s",ch);
printf("%s",ch);

Input 1: welcome18 nitk Input 2: 18Welcome nitk


Output 1: Output 2: 18W

Example 5:
scanf("%[A-Z]s", ch);
printf("%s",ch);

Input 1: 2018welcome nitk Input 2: Welcome2018 nitk


Output 1: Output 2: W
Using getchar() and putchar()
● Reading and writing single character from and to the terminal.
● We can use getchar function inside a loop to read characters one by
one till we don't read newline character (\n) or other character can
also be used as terminating character.
● Once we read newline character or terminating character,we break
loop and add '\0' character at the end of string(This is an optional for
some situation).
#include <stdio.h>
int main()
{
char ch[100], c;
int i = 0;
printf("Enter a string\n"); Output:
while((c = getchar()) != '\n') Enter a string
{ NITK2018
ch[ i ] = c;
i++; Entered string is:
} NITK2018
ch[i] = '\0’; //optional
i = 0;
printf(“entered string is:\n”);
while(ch[i] != '\0')
{
putchar(ch[i]);
i++;
} }
Arithmetic Operations on Characters
● C Programming Allows you to Manipulate on String
● Whenever the Character is used in the expression then it is
automatically Converted into Integer Value called ASCII value
● All Characters can be Manipulated with that Integer Value.(Addition,
Subtraction)
Examples :
1. ASCII value of : ‘a’ is 97
2. ASCII value of: ‘A’ is 65
3. ASCII value of: ‘Z’ is 90
4. ASCII value of : ‘z’ is 121
5.It is possible to perform arithmetic operations on the character
constants and variables.
Ex: char x = 'a' + 1 ;
printf("%d",x); // Display Result = 98 ( ascii of 'b’ )

6. What is the output of the following?


#include<stdio.h>
main()
{
char num[10]=“1947”;
printf("%d",num); }
atoi(): The C library supports a function that converts a string of digits into
their integer values.
Syntax:
int num = atoi(String);
Example :
#include<stdio.h>
main()
{
char ch[10]=“1947”; Output :
1947
int num = atoi(ch);
printf("%d",num);
}
atof():this function converts string data type to float data type.
“stdlib.h” header file supports all the type casting functions in C language.
Syntax:

float num = atof(String);


#include<stdio.h>
#include<stdlib.h>
main()
{
char c[10]=“3.142";
float num = atof(c);
printf("%f",num);
}
Length of string
The length of a string is to find number of characters in a string

=>no. of characters=9

#include <stdio.h>
int main()
{
char s[1000];
int i;
printf("Enter a string: ");
gets(s);
for(i = 0; s[i] != '\0’; i++);
printf("Length of string: %d", i);
}
Copy one string to another string
#include <stdio.h>
int main()
{
char s1[100], s2[100], i;
printf("Enter string s1: ");
gets(s1);
for(i = 0; s1[i] != '\0'; ++i)
{
s2[i] = s1[i];
}
s2[i] = '\0';
puts(s2);
return 0;
}
Putting String Together
● The process of combining two strings together is called concatenation.
Example:
Program: To concatenate two strings
while(str2[j]!='\0')
void main() {
{ str1[i]=str2[j];
char str1[25],str2[25]; j++;
int i=0,j=0; i++;
printf(" Enter First String:\n"); }
gets(str1); str1[i]='\0’; //optional
printf(" Enter Second String:\n"); printf("Concatenated
gets(str2); String”);
while(str1[i]!='\0’) puts(str1);
i++; }
Comparison of two String
In C, Comparison of string is done character by character until there is a
mismatch or any one string terminated to null character.
{
Program :To compare 2 strings
if(str1[i] == str2[i])
#include<stdio.h>
temp = 1;
main()
else
{
{ temp = 0;
char str1[5],str2[5];
break; }
int i,temp = 0;
}
printf("Enter the string1 value: ");
if(temp == 1)
gets(str1);
printf(" Enter the String2 value: "); printf("Both strings are same.

gets(str2); ");
else
printf("Both string not same.
String Handling Functions
● The C supports a large number of string handling functions defined in
<string.h> header file.
The following functions perform useful functions for string handling
supported by C.
1. strlen()
2. strcpy()
3. strcat()
4. strstr()
5. strcmp()
6. strncpy()
7. strncmp()
strlen( ):
● This function returns a type int value, which gives the length or number of
characters in a string, not including the NULL character.
● Syntax:

strlen(st
r);
#include <stdio.h>
#include <string.h>
int main()
Output:
{
enter string
char a[20]="Program”, b[20];
INDIA
printf("Enter string: ");
length of a:7
gets(b);
length of b:5
printf("Length of string a = %d \n",strlen(a));
printf(“Length of string c = %d \n",strlen(b));
}
strcpy( )
• This function copies the content of one string to the content of another string. It
takes 2 arguments.
• Syntax: strcpy(destination,
source);
#include<string.h>
Output:
#include<stdio.h> Enter string :
void main() NITK Surathkal
{ Copied string:
char src[20],dest[20]; NITK Surathkal
printf("Enter string: ");
gets(src);
strcpy(dest, src); //Content of string src is copied to string dest
printf("Copied string: ");
puts(dest);
}
strcat( )
● This function joins 2 strings. It takes two arguments, i.e., 2 strings and
resultant string is stored in the first string specified in the argument.
● Syntax :

strcat( first_string,
second_string);
#include <stdio.h>
#include <string.h>
void main() Output:
{ Enter first string:
char str1[10], str2[10}; NITK
Enter second string:
printf("Enter First String:"); Surathkal
gets(str1); Concatenated string is:
printf("\n Enter Second String:"); NITKSurathkal
gets(str2);
strcat(str1,str2); //concatenates str1 and str2 and
printf("\n Concatenated String is ");
puts(str1); //resultant string is stored in str1
}
strcmp( )
● The statement takes 2 arguments,i.e., name of two string to compare.The syntax is shown
below:
strcmp(string1,string2);
This function can return three different integer values based on the comparison:
● Zero ( 0 ): A value equal to zero when both strings are found to be identical. That is, all of
the characters in both strings are same.
● Greater than zero ( >0 ): A value greater than zero is returned when the first not
matching character in string1 have the greater ASCII value than the corresponding
character in string2
● Less than Zero ( <0 ): A value less than zero is returned when the first not matching
character in string1 have lesser ASCII value than the corresponding character in string2.
Example: Program to illustrate the use of strcmp().
#include<stdio.h>
#include<string.h>
main()
{
char str1[10]=“INDIA", str2[10]=“INDIA";
char str3[10]="NITK", str4[10]="MITK"; //ASCII value M=77 and N=78
char str5[10]="MITK", str6[10]="NITK";
printf("result=%d\n",strcmp(str1,str2)); Output:
printf("result=%d\n",strcmp(str3,str4)); Result=0
Result=1
printf("result=%d",strcmp(str5,str6));
Result=-1
}
strstr( ):
● This function is used to find occurrence of sub-string in main string.
● This function points to the first character of s2 in s1. Otherwise, a null
pointer if s2 is not present in s1.
● If s2 points to an empty string, s1 is returned.

Syntax:
strstr(first_string,
second_string);
Example: Program to illustrate the use of strstr().
#include <stdio.h>
#include<string.h>
main()
{
char s1[] = “Hello, how are you?”;
char s2[] = “are”;
if (strstr(s1,s2)!=NULL)
printf("String found\n");
else
printf("String not found\n");
}
strncpy():
● This function copies the left most n characters of the source string to
the destination string.
● Syntax:

strncpy(Destination_String, Source_String, no_of_characters);

● Example: strncpy(s1,s2,5); //copies first 5 characters of s2 into s1


strncmp():
This function compares the first n characters of two strings
Syntax:

strncmp(string1, string2, no_of_chars);

Example: strncmp(s1,s2,4);
This compares the leftmost n characters of s1 to s2 and returns:
a) 0 if they are equal
b) Negative number, if s1 sub-string is less than s2
c) Otherwise, Positive number
strncat():
● This function concatenate the left most n characters of the source string to the
destination string.
syntax:
strncat(string1, string2,no_of_chars);

Example:
What is the output of the following’s?

Example 1: char s1[4]={‘n’, ’I’, ’t’, ’k’};


char s2[4]={‘n’, ’I’, ’t’, ’k’};

printf(“%s”,strcmp(s1,s2));

Example2: char str1[5]=“nitk1”, str2[4]=“nitk”;

printf("compare=%d",strcmp(str1,str2));

Example 3: char str1[5]=“nitk1”, str2[4]=“nitk”;

printf("copy=%s", strncpy(str1,str2));
Example 5: char str1[5]=“nitk1”, str2[10]=“karnataka”;

printf("copy=%s",strncpy(str1,str2,2));

Example 6:char str1[5]=“nitk1”, str2[4]=“nitk”;

printf("merge=%s\n", strcat(str1,str2));

Example 7: char str1[4]=“nitk” , str2[10]=“how are u?”

printf("copy=%s\n", strcpy(str1,str2));

Example 8: char s1[10]=“how are u?” , str2[4]=“are”

printf("%s\n",strstr(str1,str2));
Character Manipulation Functions
1.isalpha(ch):This returns true if ch is alphabetic and false otherwise.
Alphabetic means a..z or A..Z.

2.isupper(ch):Returns true if the character was upper case. If ch was not


an alphabetic character, this returns false.

3.islower(ch):Returns true if the character was lower case. If ch was not


an alphabetic character, this returns false.

4.isdigit(ch):Returns true if the character was a digit in the range 0..9.


5. isxdigit(ch):Returns true if the character was a valid hexadecimal digit.
that is, a number from 0..9 or a letter a..f or A..F.

6. toupper(ch):This converts the character ch into its upper case letter.


This does not affect characters which are already upper case, or characters
which do not have a particular case, such as digits.

7.tolower(ch):This converts a character into its lower case. It does not


affect characters which are already lower case.
Two dimensional character array
● A 2D character array is more like a String array.
● It allows user to store multiple strings under the same name.

Declaration:

A 2D character array is declared in the following manner:

char name[5][10];

● The first subscript [5] represents the number of Strings that we want our array
to contain and the second subscript [10] represents the length of each String.
● We are giving 5*10=50 memory locations for the array elements to be stored in
the array.
Initialization
For example:
char name[5][12]={ "math”, ”physics”, ”electrical” , ”c_progm”,
”mechanical” }; Here, 5 names stored in 5 different memory locations and
each name as length 10.see the diagram below to understand how the elements
are stored in the memory location:
Read data from user
In order to take string data input from the user we need to follow the
following syntax:

char name[5][10];

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

scanf(“%s”,name[i]);
Printing array elements:
we can display all the string elements:
char name[5][10];

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

printf(“%s\n”,name[i]);
Example : program to read 10 student name.
#include<stdio.h>
main()
{
char name[10][10];
int i;
printf(“Read 10 student names\n”);
for(i=0;i<10;i++)
scanf(“%s”,name[i]);
printf(“Student names are:\n”);
for(i=0;i<10;i++)
printf(“%s\n”, name[i]); }
Program to search for a string in the string array
#include <stdio.h>
for(i=0; i<5 ;i++ )
#include <string.h>
{
int main() if((res=strcmp(name[i],key))==0)
{ temp=i;
char name[5][10],key[10]; }
int i, res, temp=0;
if(temp==0)
printf("Enter 5 strings:\n"); printf("the item does not match
for(i=0 ;i<5 ;i++ ) any name in the list");
scanf("%s", name[i]);
else
printf("Enter the string to printf("Item Found. Item in the
be searched:\n"); array exists at position - %d", temp+1);
scanf("%s", key); return 0;
}

S-ar putea să vă placă și