Module-2_Strings concepts in c programming

CHAITRAB29 57 views 66 slides May 05, 2024
Slide 1
Slide 1 of 66
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66

About This Presentation

PPts on string concepts and string related functions


Slide Content

Module-2 Strings

A string is a sequence of characters terminated by a null character ‘\0’. ‘\0’ is automatically encountered at the end of the string. Declaration of string char ch[6] ; Here, ch is a string which can store a maximum of 5 characters and 1 character is reserved for ‘\0’. Introduction

char ch[6] = “HELLO” ; char ch[6] = “Good” ; Initialization of string ch[0] ch[1] ch[2] ch[3] ch[4] ch[5] ‘H’ ‘E’ ‘L’ ‘L’ ‘O’ ‘\0’ ch[0] ch[1] ch[2] ch[3] ch[4] ch[5] ‘G’ ‘o’ ‘o’ ‘d’ ‘\0’ ‘\0’ char ch[6] = { ‘P’, ‘r’, ‘e’, ‘m’, ‘\0’ } ; ch[0] ch[1] ch[2] ch[3] ch[4] ch[5] ‘P’ ‘r’ ‘e’ ‘m’ ‘\0’ ‘\0’ char ch[6] = “Program” ; ch[0] ch[1] ch[2] ch[3] ch[4] ch[5] ‘P’ ‘r’ ‘o’ ‘g’ ‘r’ ‘a’

Initialization of string Invalid Initialization char str3[5]; str3 = “GOOD”;

I/O operations on strings scanf() char address[10] ; scanf(“%s”, address); gets() char address[10] ; gets(address); Reading Text till ~ is encountered char line[10] ; scanf("%[^~]", line); printf() char address[10] ; scanf(“%s”, address); printf(“%s”, address); puts() char address[10] ; gets(address); puts(address);

I/O operations on strings #include<stdio.h> void main() { char line[10] ; printf("Enter string\n"); gets(line); printf("The string is: "); puts(line); }

I/O operations on strings #include<stdio.h> void main() { char a[10]="GLOBAL" ; int i,j; for(i=0;i<6;i++) { for(j=0;j<=i;j++) printf("%c\t", a[j]); printf("\n"); } } #include<stdio.h> void main() { char a[10]="GLOBAL" ; int i,j; for(i=0;i<6;i++) { for(j=0;j<=i;j++) putchar(a[j]); printf("\n"); } }

Outputs: G G L G L O G L O B G L O B A G L O B A L G GL GLO GLOB GLOBA GLOBAL

Arithmetic Operations on Characters To write a character in its integer representation, we may write it as an integer. char x = ‘a’; // 97 printf(“%d\n”, x); x = ‘z’–1; printf(“%d\n”, x); // 122-1 = 121 char number[21] = “1988”; int year = atoi(number); The function atoi() converts the string “1988” (contained in number) to its numeric equivalent 1988 and assigns it to the integer variable year. String conversion functions are stored in the header file <std.lib.h>.

String concepts

Variable Length string

C Strings

Storing String

Storing strings and Characters

Differences between Strings and Character array

Character literals and String literals

String literal reference

Defining Strings

Initializing Strings

String Input and Output Function

String Input/Output

Examples of gets and fgets

puts and fputs

Example of puts and fputs

String Manipulation Functions Function Action #include<string.h> strlen() finds the length of a string excluding ‘\0’ strcpy() copies one string over another strcmp() compares two strings strcat() concatenates two strings strlwr() Converts the string to lowercase letters strupr() Converts the string to uppercase letters

String handling Functions strlen() strcpy() strcmp() strcat() strlwr() strupr() #include<string.h> void main() { char a[21] ; int len; printf("Enter a string\n"); gets(a); len=strlen(a); printf("The length of the string is: %d", len); }

String handling Functions strlen() strcpy() strcmp() strcat() strlwr() strupr() works similar to string-assignment operator. Syntax: strcpy(string1, string2); Assigns the contents of string2 to string1. string2 may be a string variable or a string constant. Example: strcpy(city, “DELHI”); will assign the string “DELHI” to the string variable city. strcpy(city1, city2); will assign the contents of the string variable city2 to the string variable city1. The size of the array city1 should be large enough to receive the contents of city2.

String handling Functions strlen() strcpy() strcmp() strcat() strlwr() strupr() #include<stdio.h> #include<string.h> void main() { char a[21],b[21] ; printf("Enter a string\n"); gets(a); strcpy(b,a); printf("The copied string is: %s",b); }

String handling Functions strlen() strcpy() strcmp() strcat() strlwr() strupr() Syntax: strcmp(string1, string2); It compares string1 with string2 (case sensitive) Returns if string1==string2 Returns value > if string1 > string2 Returns value < if string1 < string2 Examples: char name1[21]=“string”, name2[21]=“string”; strcmp(name1, name2); strcmp(name1, “John”); strcmp(“Rom”, “Ram”);

String handling Functions strlen() strcpy() strcmp() strcat() strlwr() strupr() #include<stdio.h> #include<string.h> void main() { char name1[21]="string", name2[21]="string"; int p1, p2, p3, p4; p1=strcmp(name1, name2); p2=strcmp(name1, "String"); p3=strcmp(name1, "Lohit"); p4=strcmp("RAM", "ROM"); printf("p1=%d\np2=%d\np3=%d\np4=%d\n",p1,p2,p3,p4); }

String handling Functions char name1[21]="string", name2[21]="string"; int p1, p2, p3, p4; p1=strcmp(name1, name2); p2=strcmp(name1, "String"); p3=strcmp(name1, "Lohit"); p4=strcmp("RAM", "ROM"); 1 2 3 4 5 6 - - - - 20 s t r i n g \0 0 1 2 3 4 5 6 - - 20 - - name1 name2 s t r i n g \0 0 1 2 3 4 5 6 - - 20 - - S t r i n g \0 0 1 2 3 4 5 L o h i t \0 1 2 3 R A M \0 1 2 3 R O M \0

String handling Functions strlen() strcpy() strcmp() strcat() strlwr() strupr() Joins two strings together. Syntax: strcat(string1, string2); string2 is appended to string1. It does so by removing the null character at the end of string1 and placing string2 from there. The string at string2 remains unchanged. We must make sure that the size of string1 (to which string2 is appended) is large enough to accommodate the final string.

String handling Functions strlen() strcpy() strcmp() strcat() strlwr() strupr() strcat(part1, part2);

String handling Functions strlen() strcpy() strcmp() strcat() strlwr() strupr() #include<stdio.h> #include<string.h> void main() { char name1[10]="abc", name2[10]="xyz"; printf("Before concatenation\n"); printf("name1= %s\n",name1); printf("name2= %s\n",name2); strcat(name1, name2); printf("After concatenation\n"); printf("name1= %s\n",name1); printf("name2= %s\n",name2); }

String handling Functions strlen() strcpy() strcmp() strcat() strlwr() strupr() Used to convert a given string into lowercase. Syntax: strlwr(string); #include<stdio.h> #include<string.h> void main() { char a[21]="C PROGRAM"; printf("Original string= %s\n",a); strlwr(a); printf("Converted string= %s\n",a); }

String handling Functions strlen() strcpy() strcmp() strcat() strlwr() strupr() Used to convert a given string into uppercase. Syntax: strupr(string); #include<stdio.h> #include<string.h> void main() { char a[21]="good morning"; printf("Original string= %s\n",a); strupr(a); printf("Converted string= %s\n",a); }

Programs on strings 1. Write a C program, which reads your name from the keyboard and outputs a list of ASCII codes, which represent your name. #include<stdio.h> #include<string.h> void main() { char name[21] ; int i,len; printf("Enter your name:\n"); gets(name); len=strlen(name); printf("The name is ASCII form:\n"); for(i=0;i<len;i++) printf ("%d" ,name[i]); }

Programs on strings 2. Write a C program to find length of a string without using library function. #include<stdio.h> void main() { char a[21] ; int len=0, i; printf("Enter a string\n"); gets(a); for(i=0;a[i]!='\0';i++) len++; printf("The length of the string is: %d", len); }

Programs on strings 3. Write a C program to input a string, convert lowercase letters to uppercase and vice versa without using library functions. #include <stdio.h> for(i=0;i<len;i++) #include<string.h> { void main() if(a[i]>='A' && a[i]<='Z') { a[i]=a[i]+32; char a[21]; else if(a[i]>='a' && a[i]<='z') int i, len; a[i]=a[i]-32; printf("Enter a string\n"); } gets(a); printf("The modified string is %s", a); len=strlen(a); }

Programs on strings 4. Write a C program to find total number of alphabets, digits in a string without using library functions. #include <stdio.h> for(i=0;i<len;i++) #include<string.h> { void main() if((a[i]>='A' && a[i]<='Z') || (a[i]>='a' && a[i]<='z')) { alpha++; char a[21]; else if(a[i]>='0' && a[i]<='9') int i, len, alpha=0, digit=0; digit++; printf("Enter a string\n"); } gets(a); printf("No. of alphabets=%d\nNo. of digits=%d", alpha, digit); len=strlen(a); }

Programs on strings 5. Write a C program to count total number of vowels and consonants in a string. #include<stdio.h> #include<string.h> void main() { char a[21]; int i, len, vow=0, cons=0; printf("Enter a string\n"); gets(a); strupr(a); len=strlen(a); for(i=0;i<len;i++) { if (isalpha(a[i])) { if(a[i]=='A' || a[i]=='E' || a[i]=='I' || a[i]== 'O' || a[i]=='U') vow++; else cons++; } } printf("No. of vowels = %d\n", vow); printf("No. of consonants = %d\n", cons); }

Program to Sort String Characters in C for ( i = 0; i < n-1; i ++) { for (j = i+1; j < n; j++ ) { if (string[ i ] > string[j]) { temp = string[ i ]; string[ i ] = string[j]; string[j] = temp; } } } printf ("String after sorting - %s \n", string); return 0; } #include < stdio.h > #include < string.h > int main (void) { char string[] = " simplyeasylearning "; char temp; int i , j; int n = strlen (string); printf ("String before sorting - %s \n", string);

Program to Reverse String in C #include < stdio.h > int main() { char s1[] = " TajMahal "; // String Given char s2[8]; // Variable to store reverse string int length = 0; int loop = 0; while(s1[length] != '\0’) { length++; } printf ("\ nPrinting in reverse - "); for(loop = --length; loop>=0; loop--) printf ("%c", s1[loop]); loop = 0; printf ("\ nStoring in reverse - "); while(length >= 0) { s2[length] = s1[loop]; length--; loop++; } s1[loop] = '\0'; // Terminates the string printf ("%s\n", s2); return 0; }

Program to Swap Strings in C #include < stdio.h > int main() { char s1[] = " TajMahal "; char s2[] = "Dazzling"; char ch ; int index = 0; //Character by Character approach printf ("Before Swapping - \n"); printf ("Value of s1 - %s \n", s1); printf ("Value of s2 - %s \n", s2); while(s1[index] != '\0’) { ch = s1[index]; s1[index] = s2[index]; s2[index] = ch ; index++; } printf ("After Swapping - \n"); printf ("Value of s1 - %s \n", s1); printf ("Value of s2 - %s \n", s2); return 0; }

String Copy Program in C #include < stdio.h > int main() { char s1[] = " TajMahal "; // String Given char s2[8]; // Variable to hold value int length = 0; while(s1[length] != '\0’) { s2[length] = s1[length]; length++; } s2[length] = '\0'; // Terminate the string printf ("Value in s1 = %s \n", s1); printf ("Value in s2 = %s \n", s2); return 0; }

Program to Compare Strings in C #include < stdio.h > int main() { char s1[] = "advise"; char s2[] = "advice"; int n = 0; unsigned short flag = 1; while (s1[n] != '\0’) { if(s1[n] != s2[n]) { flag = 0; break; } n++; } if(flag == 1) { printf ("%s and %s are identical\n", s1, s2); } else { printf ("%s and %s are NOT identical\n", s1, s2); } return 0; }

Program to Concatenate Strings in C #include < stdio.h > #include < string.h > int main() { char s1[10] = "Taj"; char s2[] = "Mahal"; int i , j, n1, n2; n1 = strlen (s1); n2 = strlen (s2); j = 0; for(i = n1; i< n1+n2; i++ ) { s1[i] = s2[j]; j++; } s1[i] = '\0'; printf("%s", s1); return 0; }

Implementing a Palindrome String Program in C #include < stdio.h > #include < string.h > int main() { char string[100], rev_string [100]; printf ("Enter a string: "); gets(string); strcpy ( rev_string , string); strrev ( rev_string ); if( strcmp (string, rev_string ) == 0) printf ("%s is a palindrome string.\n", string); else printf ("%s is not a palindrome string.\n", string); return 0; }

#include < stdio.h > #include < string.h > int main() { char str[] = { " abbba " }; // Start from first and // last character of str int l = 0; int h = strlen (str) - 1; WITHOUT USING LIBRARY FUNCTIONS // Keep comparing characters while they are same while (h > l) { if (str[l++] != str[h--]) { printf ("%s is not a palindrome\n", str); return 0; // will return from here } } printf ("%s is a palindrome\n", str); return 0; }

Arrays of Strings

Pointers to Strings

String/Data Conversion

String/Data Conversion Example

String/Data Conversion Example

String/Data Conversion Example

String/Data Conversion Example

String/Data Conversion Example

2.6 String/Data Conversion A common set of applications, format data by either converting a sequence of characters into corresponding data types or vice versa. Two such applications are parsing and telecommunications. C already has an extensive set of data conversion functions created for scanf and printf.

String to Data conversion The string scan function is called sscanf () . This function scans a string as though the data were coming from a file . Just like fscanf (), it requires a format string to provide the formatting parameters for the data. All fscanf () format codes are valid for the scan memory functions . Like fscanf (), the scan memory functions also return the number of variables successfully formatted. If they attempt to "read" beyond the end of string-they return an end-of-file flag. The basic concept is shown in Figure 11-24.

String to Data conversion

String to Data conversion sscanf () is a function used to read formatted input from a string. It stands for " String Scan Formatted ". It is part of the C Standard Library and is declared in the <stdio.h> header file. Syntax /The function prototype of sscanf () is : int sscanf ( const char * str , const char *format, ...); Here, str is the string from which data is to be read. format is a format string that specifies how to interpret the data in the string str. The ellipsis ... indicates that sscanf () can accept a variable number of arguments. These arguments are pointers to the variables where the extracted data will be stored. NOTE: Sscanf () is one-to-many function. It splits one string into many variables.

Example for sscanf () #include <stdio.h> int main() { char str [] = "John 25 123.45"; char name[20]; int age; float salary; sscanf ( str , "%s %d %f", name, &age, &salary); printf("Name: %s\n", name); printf("Age: %d\n", age); printf("Salary: %.2f\n", salary); return 0; } OUTPUT: Name : John Age: 25 Salary: 123.45

Data to String C onversion The string print function sprintf () follows the rules of fprintf (). Rather the sending the data to a file, however, it simply "writes" them to a string. When all data have been formatted to the string, a terminating null character added to make the result a valid string. If an error is detected, sprintf () returns any negative value, traditionally EOF. If the formatting is successful, it returns the number of characters formatted, not counting the terminating null character. The string print operation is shown in Figure 11-25.

Data to String C onversion

sprintf () is a function used to write formatted data to a string. It stands for "String Print Formatted". It is part of the C Standard Library and is declared in the <stdio.h> header file. Syntax /The function prototype of sprintf () is : int sprintf (char * str , const char *format, ...); Here, str is the character array (string) where the formatted data will be stored . format is a format string that specifies how the data should be formatted . The ellipsis ... indicates that sprintf () can accept a variable number of arguments. These arguments are the values to be formatted and inserted into the string according to the format string.

Example for sprintf () #include <stdio.h> int main() { char str [100]; int age = 25; float salary = 123.45; sprintf ( str , "My age is %d and my salary is %.2f", age, salary); printf("%s\n", str ); return 0; } OUTPUT: My age is 25 and my salary is 123.45 NOTE: Sscanf () is many-to-one function. It joins many pieces od data into one string.