Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Lecture 9

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

Structured Programming Language

CSE113

1
String
String
Strings are used for storing text/characters.
For example, "Hello World" is a string of characters.
Unlike many other programming languages, C does not have a
String type to easily create string variables. Instead, you must use
the char type and create an array of characters to make a string in C.
So, The string can be defined as the one-dimensional array of
characters terminated by a null ('\0'). The character array or the
string is used to manipulate text such as word or sentences. Each
character in the array occupies one byte of memory, and the last
character must always be 0.
The termination character ('\0') is important in a string since it is the
only way to identify where the string ends. When we define a string
as char s[10], the character s[10] is implicitly initialized with the
null in the memory.
String Declaration
There are two ways to declare a string in c language.
• By char array
• By string literal
Example of declaring string by char array in C language.

char ch[12]={‘P', ’r', ’o', ’g', ’r', ’a', ’m', ’m', ’i', ’n', ’g’, '\0'};  
As we know, array index starts from 0, so it will be represented as
in the figure given below
0 1 2 3 4 5 6 7 8 9 10 11

P r o g r a m m i n g \0

While declaring string, size is not mandatory. So we can write the


above code as given below:
char ch[]={‘P', ’r', ’o', ’g', ’r', ’a', ’m', ’m', ’i', ’n', ’g’, '\0'};  
String Declaration
There are two ways to declare a string in c language.
• By char array
• By string literal
We can also define the string by the string literal in C language. For
example: 
char ch[]=“Programming";  
In such case, '\0' will be appended at the end of the string by the
compiler.
Difference between char array and string
literal
There are two main differences between char array and literal.

• We need to add the null character '\0' at the end of the array by
ourself whereas, it is appended internally by the compiler in the
case of the character array.
• The string literal cannot be reassigned to another set of
characters whereas, we can reassign the characters of the array.
String Example in C
Let's see a simple example where a string is declared and being
printed. The '%s' is used as a format specifier for the string in c
language.

1.#include<stdio.h>    
2.int main(){    
3.  char ch1[12]={‘P', ’r', ’o', ’g', ’r', ’a', ’m', ’m', ’i', ’n', ’g’, '\0'};    
4.   char ch2[12]=" Programming";    
5.    
6.   printf("Char Array Value is: %s\n", ch1);    
7.   printf("String Literal Value is: %s\n", ch2);    
8. return 0;     Output
9.}   
Char Array Value is: Programming
String Literal Value is: Programming
Loop Through a String
Let's see a simple example where a string is declared and being
printed. The '%s' is used as a format specifier for the string in c
language.

1.#include<stdio.h>  
2.int main(){      
3.   char ch2[12]="Programming";    
4.    for(int i =0; i<11;i++){
5.     printf("%c", ch2[i]);
6.}
7. return 0;    
8.}   
Traversing String
Traversing the string is one of the most important aspects in any of
the programming languages. We may need to manipulate a very
large text which can be done by traversing the text. Traversing
string is somewhat different from the traversing an integer array. We
need to know the length of the array to traverse an integer array,
whereas we may use the null character in the case of string to
identify the end the string and terminate the loop.

Hence, there are two ways to traverse a string.


• By using the length of string
• By using the null character.
Using the length of string
1.#include<stdio.h>  
2.void main ()  
3.{  
4.    char s[12] = "Programming";  
5.    int i = 0;   
6.    int count = 0;  
7.    while(i<11)  
8.    {  
9.        if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o')  
10.        {  
11.            count ++;   Output
The number of vowels 3
12.        }  
13.        i++;  
14.    }  
15.    printf("The number of vowels %d",count);  
16.} 
Using the null character
1.#include<stdio.h>  
2.void main ()  
3.{  
4.    char s[12] = "Programming";  
5.    int i = 0;   
6.    int count = 0;  
7.    while(s[i] != NULL)  
8.    {  
9.        if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o')  
10.        {  
11.            count ++;   Output
The number of vowels 3
12.        }  
13.        i++;  
14.    }  
15.    printf("The number of vowels %d",count);  
16.}  
Accepting string as the input
1.#include<stdio.h>  
2.void main ()  
3.{  
4.    char s[20];  
5.    printf("Enter the string?\n");  
6.    scanf("%s",s);  
7.    printf("You entered %s",s);  
8.}  

It is clear from the output that, the above code will not work for
space separated strings. To make this code working for the space
separated strings, the minor changed required in the scanf function,
i.e., instead of writing scanf("%s",s), we must write: scanf("%[^\
n]s",s) which instructs the compiler to store the string s while the
new line (\n) is encountered.
To store the space-separated strings
1.#include<stdio.h>  
2.void main ()  
3.{  
4.    char s[20];  
5.    printf("Enter the string?");  
6.    scanf("%[^\n]s",s);  
7.    printf("You entered %s",s);  
8.}  

It is clear from the output that, the above code will not work for
space separated strings. To make this code working for the space
separated strings, the minor changed required in the scanf function,
i.e., instead of writing scanf("%s",s), we must write: scanf("%[^\
n]s",s) which instructs the compiler to store the string s while the
new line (\n) is encountered.
To store the space-separated strings
C gets() function
The gets() function enables the user to enter some characters
followed by the enter key. All the characters entered by the user get
stored in a character array. The null character is added to the array
to make it a string. The gets() allows the user to enter the space-
separated strings. It returns the string entered by the user.

//Reading string using gets()


1.#include<stdio.h>  
2.void main ()  
3.{  
4.    char s[30];  
5.    printf("Enter the string? ");  
6.    gets(s);  
7.    printf("You entered %s",s);  
8.}  
fgets() Function
The gets() function is risky to use since it doesn't perform any array
bound checking and keep reading the characters until the new line
(enter) is encountered. It suffers from buffer overflow, which can
be avoided by using fgets(). The fgets() makes sure that not more
than the maximum limit of characters are read. Consider the
following example.
Syntax: fgets(name, sizeof(name), stdin); // read string
1.#include<stdio.h>  
2.void main()   
3.{   
4.   char str[5];   
5.   printf("Enter the string? \n");  
6.   fgets(str, sizeof(str), stdin);   
7.   printf("%s", str);   
8.}   
puts() Function
The puts() function is very much similar to printf() function. The puts()
function is used to print the string on the console which is previously
read by using gets() or scanf() function. The puts() function returns an
integer value representing the number of characters being printed on the
console. Since, it prints an additional newline character with the string,
which moves the cursor to the new line on the console, the integer value
returned by puts() will always be equal to the number of characters
present in the string plus 1.
1.#include<stdio.h>     
2.int main(){    
3.char name[50];    
4.printf("Enter your name: ");    
5.gets(name); //reads string from user    
6.printf("Your name is: ");    
7.puts(name);  //displays string    
8.return 0; }    
C String Functions
There are many important string functions defined in "string.h" library.
C String Length: strlen() function
The strlen() function returns the length of the given string. It doesn't
count null character '\0’.
1.#include<stdio.h>  
2.#include <string.h>    
3.int main(){    
4.char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};    
5.   printf("Length of string is: %d",strlen(ch));     Output:
6. return 0;     Length of string is: 10
7.}    
Sizeof() and strlen() behaves differently, as sizeof() includes the \0
character when counting:
char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
printf("%d", strlen(alphabet));   // 26
printf("%d", sizeof(alphabet));   // 27

You might also like