Nothing Special   »   [go: up one dir, main page]

Strings

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

Strings

• Introduction
• Declaring and Storing strings
• Initializing strings
• Accessing elements of the strings
• Operations on strings
• Array of strings
Introduction
• Computers are widely used for word processing applications such as creating, updating, inserting and
modifying the textual data – We need to search for a particular pattern within a text, delete it or replace it
with another pattern.
• In C, String is a null-terminated character array.
• After the last character, a null character ('\0') is stored to signify the end of the character array. For example, if
we write char str[] = "HELLO";
• Here, we are declaring an array that has five characters, namely, H, E, L, L, and O. Apart from these
characters, a null character ('\0') is stored at the end of the string. So, the internal representation of the string
becomes HELLO'\0’.
• To store a string of length 5, we need 5 + 1 locations (1 extra for the null character). The name of the
character array (or the string) is a pointer to the beginning of the string.
• If we had declared str as char str[5] = "HELLO"; then the null character will not be appended
automatically to the character array. This is because str can hold only 5 characters and the characters in
HELLO have already filled the space allocated to it.
Difference between character storage and
string storage
Accessing the elements of a string
• We use subscripts to access the elements of a string.
• The subscript starts with a zero (0). All the characters of a string are stored in successive memory locations

• String is a sequence of characters


• 1000, 1001, 1002, etc., are the memory
addresses of individual characters.
• For simplicity, the figure shows that H is
stored at memory location 1000 but in
reality, the ASCII code of a character is
stored in the memory and not the
character itself. So, at address 1000, 72
will be stored as the ASCII code for H is
72.
Declaring a string
• char str[size];
• We can store size–1 characters in the array because the last character would be the null character.
• The other way to initialize a string is to initialize it as an array of characters. For example,
• char str[] = {'H', 'E', 'L', 'L', 'O', '\0’};
• W have explicitly added the null character. Also observe that we have not mentioned the size of the string. Here, the
compiler will automatically calculate the size based on the number of characters. So, in this example six memory locations
will be reserved to store the string variable, str.
• We can also declare a string with size much larger than the number of elements that are initialized.
• For example, consider the statement below.
• char str [10] = "HELLO";
• In such cases, the compiler creates an array of size 10; stores "HELLO" in it and finally terminates the string with a null
character. Rest of the elements in the array are automatically initialized to NULL. Now consider the following statements:
• char str[3];
• str = "HELLO";
• The above initialization statement is illegal in C and would generate a compile-time error because of two reasons.
• First, the array is initialized with more elements than it can store.
• Second, initialization cannot be separated from declaration.
Reading strings
• If we declare a string by writing char str[100];
• Then str can be read by the user in three ways:
1. Using scanf function  scanf("%s", str);
• Drawback  The function terminates as soon as it finds a blank space.
• For example, if the user enters Hello World, then the str will contain only Hello.
• This is because the moment a blank space is encountered, the string is terminated by the scanf() function.
• You may also specify a field width to indicate the maximum number of characters that can be read.
Remember that extra characters are left unconsumed in the input buffer.
• Unlike int, float, and char values, %s format does not require the ampersand before the variable str.
• Using & operand with a string variable in the scanf statement generates an error.
Reading strings contd…
2. Using gets() function  gets(str);
• gets() is a simple function that overcomes the drawbacks of the scanf() function.
• The gets() function takes the starting address of the string which will hold the input. The string
inputted using gets() is automatically terminated with a null character.

3. Strings can also be read by calling the getchar() function repeatedly to read a sequence of
single characters (unless a terminating character is entered) and simultaneously storing it in a
character array
Reading strings contd..
3. Using getchar(),getch()or getche() function repeatedly.

i=0;()
ch = getchar;// Get a character
while(ch != '*’)
{
str[i] = ch;// Store the read character in str
i++;
ch = getchar();// Get another character
}

str[i] = '\0';// Terminate str with null character

• In this method, you have to deliberately append the string with a null character.
Reading strings using getchar() repeatedly
#include <stdio.h>
int main()
{
int i = 0;
char ch;
char str[10];
printf("Enter a character \n");
ch = getchar();
while(ch!='*')
{
ch = getchar();
str[i] = ch;
i++;
}
str[i] = '\0’;
printf(str);
return 0;
}
Writing strings
•Strings can be displayed on the screen using the following three ways:
•Using printf() function,
•Using puts() function, and
•Using putchar() function repeatedly.
•Using printf() function  printf("%s", str);
•Use format specifier %s to output a string.
•‘&’ character is not used with the string variable.
•Width and precision specifications can also be used along with %s.
•The width specifies the minimum output field width. If the string is short, the extra space is either left padded or right padded.
A negative width left pads short string rather than the default right justification.
•The precision specifies the maximum number of characters to be displayed, after which the string is truncated.
•For example, printf ("%5.3s", str);
•The above statement would print only the first three characters in a total field of five characters. Also these characters would
be right justified in the allocated width.
•To make the string left justified, we must use a minus sign. For example,
•printf ("%–5.3s", str);
•When the field width is less than the length of the string, the entire string will be printed. If the number of characters
to be printed is specified as zero, then nothing is printed on the screen.
Writing strings

• Using puts() function

• puts(str);

• puts() is a simple function that overcomes the drawbacks of the printf() function.

• Using putchar() function  Strings can also be written by calling the putchar() function repeatedly to print a sequence of single
characters.

i=0;

while(str[i] != '\0')

putchar(str[i]);// Print the character on the screen

i++;

}
Operations on strings
• Finding the length of a string
• Converting characters of a string into Uppercase / Lowercase
• Appending a string to another string
• Comparing two strings
• Reversing a string
• Extracting a substring from a string
• Inserting a string in the main string
• Pattern matching
• Deleting a substring from the main string
• Replacing a pattern with another pattern in the main string
Finding the length of a string
• The number of characters in a string constitutes the length of the string.
• Blank spaces are also counted as characters in the string
• Write a program to find the length of a string.
#include <stdio.h>
int main()
{
char str[100];
int i = 0, length;
printf("\n Enter the string : ");
fgets(str, 100, stdin);
while(str[i] != '\0’) stdin  To read from
i++; the standard input
length = i;
printf("\n The length of the string is : %d", length);return 0;
}
OUTPUT: Enter the string : aiml
The length of the string is : 5
Converting characters of a string into Uppercase / Lowercase
• The ASCII code for A–Z varies from 65 to 91 and the ASCII code for a–z ranges from 97 to 123.
• To convert a lower case character into uppercase  Subtract 32 from the ASCII value of the character.
• To convert an upper case character into lower case  Add 32 to the ASCII value of the character.

• The library functions toupper() and tolower() which are defined in ctype.h convert a character into
upper and lower case, respectively.
Write a program to convert the lower case characters of a string into upper case.
#include <stdio.h>
int main()
{
char str[100], upper_str[100];
int i=0;
printf("\n Enter the string :");
fgets(str);
while(str[i] != '\0')
{
if(str[i]>='a' && str[i]<='z')
upper_str[i] = str[i] - 32;
else
upper_str[i] = str[i];
i++;
}
upper_str[i] = '\0';
printf("\n The string converted into upper case is : ");
puts(upper_str);
return 0;
}
Appending a string to another string

• Copying the contents of the source string at the end of the destination string.

• For example, if S1 and S2 are two strings, then appending S1 to S2 means we have to add the
contents of S1 to S2. So, S1 is the source string and S2 is the destination string.

• The appending operation would leave the source string S1 unchanged and the destination string

S2 = S2 + S1.

• The library function strcat(s1, s2) which is defined in string.h concatenates string s2 to s1.
Write a program to append a string to another string.
#include <stdio.h>
int main()
{
char Dest_Str[100], Source_Str[50];
int i=0, j=0;
printf("\n Enter the source string : ");
Output
fgets(Source_Str, 50, stdin);
Enter the source string : How are
printf("\n Enter the destination string : ");
you?
fgets(Dest_Str, 100, stdin);
Enter the destination string :
while(Dest_Str[i] != '\0')
i++;
Hello,
while(Source_Str[j] != '\0') After appending, the destination
{ string is : Hello, How are you?
Dest_Str[i] = Source_Str[j];
i++;
j++;
}
Dest_Str[i] = '\0';
printf("\n After appending, the destination string is : ");
puts(Dest_Str);
return 0;
}
Comparing two strings
• If S1 and S2 are two strings, then comparing the two strings will give either of the following
results:

(a) S1 and S2 are equal

b) S1>S2, when in dictionary order, S1 will come after S2

(c) S1<S2, when in dictionary order, S1 precedes S2

• To compare the two strings, each and every character is compared from both the strings. If all the
characters are the same, then the two strings are said to be equal.

• The library function strcmp(s1, s2) which is defined in string.h compares string s1 with s2.
Write a program to compare two strings
#include <stdio.h>
#include <string.h> }
int main() if(len1!=len2)
{ printf("\n The two strings are not equal");
if(same == 0)
char str1[50], str2[50];
{
int i=0, len1=0, len2=0, same=0; if(str1[i]>str2[i])
printf("\n Enter the first string : "); printf("\n String 1 is greater than string 2");
fgets(str1, 50, stdin); else if(str1[i]<str2[i])
printf("\n Enter the second string : "); printf("\n String 2 is greater than string 1");
}
fgets(str2, 50, stdin);
return 0;
len1 = strlen(str1); }
len2 = strlen(str2);
if(len1 == len2)
{
while(i<len1)
Output
{
Enter the first string : Hello
if(str1[i] == str2[i])
i++;
Enter the second string : Hello
else break;
The two strings are equal
}
if(i==len1)
{
same=1;
printf("\n The two strings are equal");
Reversing a string

• If S1 = "HELLO", then reverse of S1 = "OLLEH".


• To reverse a string, we just need to swap the first character with the last, second character with the
second last character, and so on.
• The library function strrev(s1) which is defined in string.h reverses all the characters in the string
except the null character.
Write a program to reverse a given string
#include <stdio.h>
#include <string.h>
int main()
{
char str[100], reverse_str[100], temp;
int i=0, j=0; Output:
printf("\n Enter the string : ");
Enter the string: Hi there
fgets(str, 100, stdin);
j = strlen(str) - 1; The reversed string is: ereht iH
while(i < j)
{
temp = str[j];
str[j] = str[i];
str[i] = temp;
i++;
j_--;
}
printf("\n The reversed string is : ");
puts(str);
return 0;
}
Extracting a substring from a string
• To extract a substring from a given string, we need the following three parameters:
1. the main string,
2. the position of the first character of the substring in the given string, and
3. the maximum number of characters/length of the substring.
• For example, if we have a string
str[] = "Welcome to the world of programming";
Then,
SUBSTRING(str, 15, 5) = world
Write a program to extract a substring from the middle of a given string
#include <stdio.h> substr[j] = '\0';
int main() printf("\n The substring is :
{ ");
char str[100], substr[100]; puts(substr);
int i=0, j=0, n, m; return 0;
printf("\n Enter the main string : "); }
fgets(str, 100, stdin);
printf("\n Enter the position from which to start the substring:
");
scanf("%d", &m);
printf("\n Enter the length of the substring: ");
scanf("%d", &n); OUTPUT:
i=m; Enter the main string : Hi there
while(str[i] != '\0' && n>0) Enter the position from which to
{ start the substring: 1
substr[j] = str[i]; Enter the length of the substring: 4
i++; The substring is : i th
j++;
n––;
}
Inserting a string in the main string
• The insertion operation inserts a string S in the main text T at the kth
position.
• The general syntax of this operation is
• INSERT(text, position, string).
• For example,
• INSERT("XYZXYZ", 3, "AAA") = "XYZAAAXYZ"
Write a program to insert a string in the main text.
#include <stdio.h>
int main() else
{ {
char text[100], str[20], ins_text[100]; ins_text[j] = text[i];
int i=0, j=0, k=0, pos; j++;
printf("\n Enter the main text : "); }
fgets(text, 100, stdin);
i++;
printf("\n Enter the string to be inserted : ");
fgets(str, 20, stdin);
}
printf("\n Enter the position at which the string has to be inserted: "); ins_text[j] = '\0';
scanf("%d", &pos); printf("\n The new string is : ");
while(text[i] != '\0') puts(ins_text);
{ return 0;
if(i==pos) }
{
while(str[k] != '\0') Output
{ Enter the main text : newsman
ins_text[j] = str[k];
Enter the string to be inserted :
j++;
k++; paper
} Enter the position at which the
} string has to be inserted: 4
The new string is: newspaperman
Pattern Matching
• Returns the position in the string where the string pattern first occurs.
• For example, INDEX("Welcome to the world of programming", "world") = 15
• However, if the pattern does not exist in the string, the INDEX function returns 0.
Delete a substring from the main string

• The deletion operation deletes a substring from a given text.


• DELETE(text, position, length). For example,
• DELETE("ABCDXXXABCD", 4, 3) = "ABCDABCD"
Write a program to delete a substring from a text
#include <stdio.h>
int main() if(str[j]=='\0')
{ copy_loop=k;
new_text[n] = text[copy_loop];
char text[200], str[20], new_text[200];
i++;
int i=0, j=0, found=0, k, n=0, copy_loop=0; copy_loop++;
printf("\n Enter the main text : "); n++;
fgets(text, 200, stdin);
}
new_text[n]='\0';
printf("\n Enter the string to be deleted : "); printf("\n The new string is : ");
fgets(str, 20, stdin); puts(new_text);
while(text[i]!='\0') return 0;
}
{
j=0, found=0, k=i;
Output
while(text[k]==str[j] && str[j]!='\0') Enter the main text : Hello, how are
{ you?
k++; Enter the string to be deleted : , how
are you?
j++;
The new string is : Hello
}
Replacing a pattern with another pattern in a string

• The replacement operation is used to replace the pattern P1 by another pattern P2. This is done by
writing REPLACE(text, pattern1, pattern2).
• For example,
• ("AAABBBCCC", "BBB", "X") = AAAXCCC
• ("AAABBBCCC", "X", "YYY")= AAABBBCC
• In the second example, there is no change as X does not appear in the text.
Write a program to replace a pattern with another pattern in the text
#include <stdio.h> if(pat[j]=='\0')
main() {
copy_loop=k;
{
while(rep_pat[rep_index] !='\0')
char str[200], pat[20], new_str[200], rep_pat[100]; {
int i=0, j=0, k, n=0, copy_loop=0, rep_index=0; new_str[n] = rep_pat[rep_index];
printf("\n Enter the string : "); rep_index++;
n++;
fgets(str, 200, stdin); }
printf("\n Enter the pattern to be replaced: "); }
fgets(pat, 20, stdin); new_str[n] = str[copy_loop];
i++;
printf("\n Enter the replacing pattern: "); copy_loop++;
fgets(rep_pat, 100, stdin); n++;
while(str[i]!='\0') }
new_str[n]='\0';
{
printf("\n The new string is : ");
j=0,k=i; puts(new_str);
while(str[k]==pat[j] && pat[j]!='\0’) return 0;
{
Output
k++; Enter the string : How ARE you?
j++; Enter the pattern to be replaced : ARE
} Enter the replacing pattern : are
The new string is : How are you?
Array of Strings & Memory Representation of an array of strings.

• An array of strings is declared as


• char names[20][30];
• Here, the first index will specify how many strings are needed and the second index will specify the length of
every individual string.

Memory Representation of an array of strings:

char name[5][10] = {"Ram", "Mohan", "Shyam", "Hari", "Gopal"};

• By declaring the array names, we allocate 50


bytes.
• But the actual memory occupied is 27 bytes.
• Thus, we see that about half of the memory
allocated is wasted.
Write a program to sort the names of students.
#include <stdio.h>>
#include <string.h> Output
int main() Enter the number of students :
{ 3
char names[5][10], temp[10];
int i, n, j; Enter the name of student 1 :
printf("\n Enter the number of students : ");
Goransh
scanf("%d", &n);
for(i=0;i<n;i++) Enter the name of student 2 :
{
Aditya
printf("\n Enter the name of student %d : ", i+1);
gets(names[i]); Enter the name of student 3 :
}
for(i=0;i<n;i++)
Sarthak
{ Names of the students in
for(j=0;j<n–i–1;j++)
{
alphabetical order are : Aditya
if(strcmp(names[j], names[j+1])>0) Goransh Sarthak
{
strcpy(temp, names[j]);
strcpy(names[j], names[j+1]);
strcpy(names[j+1], temp);
}
}
}
printf("\n Names of the students in alphabetical order are : ");
for(i=0;i<n;i++)
puts(names[i]);
return 0;
}
Write a program to read multiple lines of text and then count the number of characters,
words, and lines in the text.
#include <stdio.h>
int main()
{
char str[1000];
int i=0, word_count = 1, line_count =1, char_count = 1;
Output:
printf("\n Enter a * to end");
printf("\n Enter the text : "); Enter a ‘*’ to end
scanf("%c", &str[i]); Enter the text : Hi there*
while(str[i] != '*')
{ The total count of words is : 2
i++; The total count of lines is : 1
scanf("%c", &str[i]);
}
The total count of characters is : 9
str[i] = '\0';
i=0;
while(str[i] != '\0')
{
if(str[i] == '\n' || i==79)
line_count++;
if(str[i] == ' ' &&str[i+1] != ' ')
word_count++;
char_count++;
i++;
}
printf("\n The total count of words is : %d", word_count);
printf("\n The total count of lines is : %d", line_count);
printf("\n The total count of characters is : %d", char_count);
return 0;
}
Write a program to find whether a string is a palindrome or not.
#include <stdio.h>
#include <string.h>

int main(){
char string1[20]; Output:
int i, length; Enter a string: madam
int flag = 0;
madam is a palindrome
printf("Enter a string:");
scanf("%s", string1);

length = strlen(string1);

for(i=0;i < length ;i++){


if(string1[i] != string1[length-i-1]){
flag = 1;
break;
}
}

if (flag) {
printf("%s is not a palindrome", string1);
}
else {
printf("%s is a palindrome", string1);
}
return 0;
}

You might also like