Strings Programming with Sikander
Objectives In this chapter you will learn about • Declaring and Initializing Strings • Reading Strings from the terminal • Writing strings to screen • Character handling library functions • String handling library functions Programming with Sikander | C Programming | Strings
Introduction • There is no String data type in C • String in C are simply array of characters terminated with null character (character ‘0’) • A set of characters defined within double quotation is a “string constant” Programming with Sikander | C Programming | Strings
Declaring and Initializing String • Allocate space for a string just like any other array: char string[16]; • Space for string must contain room for terminating null character • we can initialize string with a string constant: • char s1[ ] = “SIKANDER"; • We can initialise a string using = but we can't set a string using this at other times; instead we need to use a function which will be discussed later • We can initialize string with a sequence of characters similar to initializing arrays • char s2[ ] = {‘S’ , ’I’ , ’K’ , ’A’ , ’N’ , ’D’ , ’E’ ,’R’}; Programming with Sikander | C Programming | Strings
Programming with Sikander | C Programming | Strings
Programming with Sikander | C Programming | Strings
Programming with Sikander | C Programming | Strings
Common Programming Errors char subject[4]=“RTOS”; // No space for storing null character Programming with Sikander | C Programming | Strings
Reading String No Need of & • What if the array is not large enough to hold the input? – characters will be stored into memory locations past the end of the array – will result in run-time memory access violation error ! Programming with Sikander | C Programming | Strings
Reading a string : Better Approach #define MAX_BUFFER 20 char buffer[MAX_BUFFER]; fgets(buffer, MAX_BUFFER, stdin);  fgets is similar to gets, but:  It takes a second argument as max size  it takes a third argument, a file pointer; in our case standard input  it stores into buffer no more than MAX_BUFFER - 1 chars (extra characters are ignored), so memory violation error won’t occur Programming with Sikander | C Programming | Strings
fgets Try with input RAJU SIKANDER Programming with Sikander | C Programming | Strings
fgets fgets also read n as part of input Programming with Sikander | C Programming | Strings
Reading multiword string  scanf(“ %[^n]s”, str);  fgets(str, SIZE, stdin); Programming with Sikander | C Programming | Strings
Printing String char buffer[] = “PROGRAMMING WITH SIKANDER”; printf(“%s”, buffer); // or puts(buffer); prints characters up to null character Programming with Sikander | C Programming | Strings
Functions for Manipulating Strings  C provides a large number of functions for manipulating strings and characters.  Character handling library  Includes functions to perform useful tests and manipulations of character data  Each function receives a character (an int)  String handling library has functions to  Manipulate string data  Search strings  Tokenize strings  Determine string length Programming with Sikander | C Programming | Strings
Useful Character-handling library functions. Prototype Function Description int isdigit( int c ); Returns a non-zero value if c is a digit and 0 (false) otherwise. int isalpha( int c ); Returns a non-zero value if c is a letter and 0 otherwise. int isalnum( int c ); Returns a non-zero value if c is a digit or a letter and 0 otherwise. int isxdigit( int c ); Returns a non-zero value if c is a hexadecimal digit character and 0 otherwise. int islower( int c ); Returns a non-zero value if c is a lowercase letter and 0 otherwise. int isupper( int c ); Returns a non-zero value if c is an uppercase letter and 0 other­ wise. int tolower( int c ); If c is an uppercase letter, tolower returns c as a lowercase letter. Otherwise, tolower returns the argument unchanged. int toupper( int c ); If c is a lowercase letter, toupper returns c as an uppercase letter. Otherwise, toupper returns the argument unchanged. Include ctype.h when using these functions
 Write a Program to read a string and i. count number of digits ii. Count number of Uppercase alphabets iii. Count number of Lowercase alphabets
Program to count number of digits, uppercase and lowercase characters. Programming with Sikander | C Programming | Strings
 Write a Program to verify if the given password (string) is strong or not.  A strong password consists of  Atleast 1 Upper case alphabet  Atleast 1 Lower case alphabet  Atleast 1 digit  Atleast 1 non alphanumic Programming with Sikander | C Programming | Strings
Function to convert lower case to uppercase and vice versa Programming with Sikander | C Programming | Strings
String library functions. Include string.h when using these functions Function Name Function Description strcpy(Target_String_Var,Sr c_String) Copies the string value Src_String into the string variable Target_String_Var. strcat(Target_String_Var,Sr c_String) Concatenates the string value Src_String onto the end of the C-string in the string variable Target_String_Var. strlen(Src_String) Returns an integer equal to the length of Src_String. (The null character, ’0’, is not counted in the length.) strcmp(String_1,String_2) Returns 0 if String_1 and String_2 are the same. Returns a value < 0 if String_1 is less than String_2. Returns a value > 0 if String_1 is > than String_2 ( that is returns a nonzero value if String_1 and String_2 are different). Few Important Functions for Manipulating Strings : Unrestricted
strlen - calculate the length of a string Programming with Sikander | C Programming | Strings  size_t strlen(const char *s);  The strlen() function calculates the length of the string pointed to by s, excluding the terminating null byte (' 0').
strlen - calculate the length of a string Programming with Sikander | C Programming | Strings
strlen - calculate the length of a string Programming with Sikander | C Programming | Strings
strcpy – copy a String  char *strcpy(char *dest, const char *src);  The strcpy() function copies the string pointed to by src, including the terminating null byte ('0'), to the buffer pointed to by dest.  The destination string dest must be large enough to receive the copy. Programming with Sikander | C Programming | Strings
strcpy – copy a String Programming with Sikander | C Programming | Strings
Comparing String Programming with Sikander | C Programming | Strings
strcmp – compare two strings Programming with Sikander | C Programming | Strings  int strcmp(const char *s1, const char *s2);  The strcmp() function compares the two strings s1 and s2. Return value Description < 0 s1 is less than s2 = 0 s1 matches s2 (the strings are equal) > 0 s1 is greater than s2
strcmp – compare two strings Programming with Sikander | C Programming | Strings
strcmp – compare two strings Programming with Sikander | C Programming | Strings
strcmp – compare two strings Programming with Sikander | C Programming | Strings
strcat – concatenate two strings Programming with Sikander | C Programming | Strings  char *strcat(char *dest, const char *src);  The strcat() function appends the src string to the dest string, overwriting the terminating null byte ('0') at the end of dest.  The dest string must have enough space for the result.
Programming with Sikander | C Programming | Strings
Programming with Sikander | C Programming | Strings  After strcpy  After strcat
String library functions. Include string.h when using these functions Function Name Function Description strncpy(Target_String_Var, Src_String, Limit) The same as the two-argument strcpy except that at most Limit characters are copied. strncat(Target_String_Var, Src_String, Limit) The same as the two argument strcat except that at most Limit characters are appended. strncmp(String_1,String_2, Limit) The same as the two-argument strcat except that at most Limit characters are compared. Functions for Manipulating Strings : Restricted
strncmp
Storing Multiple strings  char name[10]; // Store 1 name of max 9 characters  char names[5][10]; // Store 5 names with each names upto 9 characters.
Storing Multiple strings
Accessing individual strings names[0] SIKANDER names[1] NIHAD
Sorting of Strings Programming with Sikander | C Programming | Strings
THANK YOU Programming with Sikander | C Programming | Strings

Strings in C - covers string functions

  • 1.
  • 2.
    Objectives In this chapteryou will learn about • Declaring and Initializing Strings • Reading Strings from the terminal • Writing strings to screen • Character handling library functions • String handling library functions Programming with Sikander | C Programming | Strings
  • 3.
    Introduction • There isno String data type in C • String in C are simply array of characters terminated with null character (character ‘0’) • A set of characters defined within double quotation is a “string constant” Programming with Sikander | C Programming | Strings
  • 4.
    Declaring and Initializing String •Allocate space for a string just like any other array: char string[16]; • Space for string must contain room for terminating null character • we can initialize string with a string constant: • char s1[ ] = “SIKANDER"; • We can initialise a string using = but we can't set a string using this at other times; instead we need to use a function which will be discussed later • We can initialize string with a sequence of characters similar to initializing arrays • char s2[ ] = {‘S’ , ’I’ , ’K’ , ’A’ , ’N’ , ’D’ , ’E’ ,’R’}; Programming with Sikander | C Programming | Strings
  • 5.
    Programming with Sikander| C Programming | Strings
  • 6.
    Programming with Sikander| C Programming | Strings
  • 7.
    Programming with Sikander| C Programming | Strings
  • 8.
    Common Programming Errors char subject[4]=“RTOS”; //No space for storing null character Programming with Sikander | C Programming | Strings
  • 9.
    Reading String No Needof & • What if the array is not large enough to hold the input? – characters will be stored into memory locations past the end of the array – will result in run-time memory access violation error ! Programming with Sikander | C Programming | Strings
  • 10.
    Reading a string: Better Approach #define MAX_BUFFER 20 char buffer[MAX_BUFFER]; fgets(buffer, MAX_BUFFER, stdin);  fgets is similar to gets, but:  It takes a second argument as max size  it takes a third argument, a file pointer; in our case standard input  it stores into buffer no more than MAX_BUFFER - 1 chars (extra characters are ignored), so memory violation error won’t occur Programming with Sikander | C Programming | Strings
  • 11.
    fgets Try with input RAJU SIKANDER Programmingwith Sikander | C Programming | Strings
  • 12.
    fgets fgets also readn as part of input Programming with Sikander | C Programming | Strings
  • 13.
    Reading multiword string scanf(“ %[^n]s”, str);  fgets(str, SIZE, stdin); Programming with Sikander | C Programming | Strings
  • 14.
    Printing String char buffer[]= “PROGRAMMING WITH SIKANDER”; printf(“%s”, buffer); // or puts(buffer); prints characters up to null character Programming with Sikander | C Programming | Strings
  • 15.
    Functions for ManipulatingStrings  C provides a large number of functions for manipulating strings and characters.  Character handling library  Includes functions to perform useful tests and manipulations of character data  Each function receives a character (an int)  String handling library has functions to  Manipulate string data  Search strings  Tokenize strings  Determine string length Programming with Sikander | C Programming | Strings
  • 16.
    Useful Character-handling library functions. PrototypeFunction Description int isdigit( int c ); Returns a non-zero value if c is a digit and 0 (false) otherwise. int isalpha( int c ); Returns a non-zero value if c is a letter and 0 otherwise. int isalnum( int c ); Returns a non-zero value if c is a digit or a letter and 0 otherwise. int isxdigit( int c ); Returns a non-zero value if c is a hexadecimal digit character and 0 otherwise. int islower( int c ); Returns a non-zero value if c is a lowercase letter and 0 otherwise. int isupper( int c ); Returns a non-zero value if c is an uppercase letter and 0 other­ wise. int tolower( int c ); If c is an uppercase letter, tolower returns c as a lowercase letter. Otherwise, tolower returns the argument unchanged. int toupper( int c ); If c is a lowercase letter, toupper returns c as an uppercase letter. Otherwise, toupper returns the argument unchanged. Include ctype.h when using these functions
  • 18.
     Write aProgram to read a string and i. count number of digits ii. Count number of Uppercase alphabets iii. Count number of Lowercase alphabets
  • 19.
    Program to countnumber of digits, uppercase and lowercase characters. Programming with Sikander | C Programming | Strings
  • 20.
     Write aProgram to verify if the given password (string) is strong or not.  A strong password consists of  Atleast 1 Upper case alphabet  Atleast 1 Lower case alphabet  Atleast 1 digit  Atleast 1 non alphanumic Programming with Sikander | C Programming | Strings
  • 21.
    Function to convertlower case to uppercase and vice versa Programming with Sikander | C Programming | Strings
  • 22.
    String library functions. Includestring.h when using these functions Function Name Function Description strcpy(Target_String_Var,Sr c_String) Copies the string value Src_String into the string variable Target_String_Var. strcat(Target_String_Var,Sr c_String) Concatenates the string value Src_String onto the end of the C-string in the string variable Target_String_Var. strlen(Src_String) Returns an integer equal to the length of Src_String. (The null character, ’0’, is not counted in the length.) strcmp(String_1,String_2) Returns 0 if String_1 and String_2 are the same. Returns a value < 0 if String_1 is less than String_2. Returns a value > 0 if String_1 is > than String_2 ( that is returns a nonzero value if String_1 and String_2 are different). Few Important Functions for Manipulating Strings : Unrestricted
  • 23.
    strlen - calculatethe length of a string Programming with Sikander | C Programming | Strings  size_t strlen(const char *s);  The strlen() function calculates the length of the string pointed to by s, excluding the terminating null byte (' 0').
  • 24.
    strlen - calculatethe length of a string Programming with Sikander | C Programming | Strings
  • 25.
    strlen - calculatethe length of a string Programming with Sikander | C Programming | Strings
  • 26.
    strcpy – copya String  char *strcpy(char *dest, const char *src);  The strcpy() function copies the string pointed to by src, including the terminating null byte ('0'), to the buffer pointed to by dest.  The destination string dest must be large enough to receive the copy. Programming with Sikander | C Programming | Strings
  • 27.
    strcpy – copya String Programming with Sikander | C Programming | Strings
  • 28.
    Comparing String Programming withSikander | C Programming | Strings
  • 29.
    strcmp – comparetwo strings Programming with Sikander | C Programming | Strings  int strcmp(const char *s1, const char *s2);  The strcmp() function compares the two strings s1 and s2. Return value Description < 0 s1 is less than s2 = 0 s1 matches s2 (the strings are equal) > 0 s1 is greater than s2
  • 30.
    strcmp – comparetwo strings Programming with Sikander | C Programming | Strings
  • 31.
    strcmp – comparetwo strings Programming with Sikander | C Programming | Strings
  • 32.
    strcmp – comparetwo strings Programming with Sikander | C Programming | Strings
  • 33.
    strcat – concatenatetwo strings Programming with Sikander | C Programming | Strings  char *strcat(char *dest, const char *src);  The strcat() function appends the src string to the dest string, overwriting the terminating null byte ('0') at the end of dest.  The dest string must have enough space for the result.
  • 34.
    Programming with Sikander| C Programming | Strings
  • 35.
    Programming with Sikander| C Programming | Strings  After strcpy  After strcat
  • 36.
    String library functions. Includestring.h when using these functions Function Name Function Description strncpy(Target_String_Var, Src_String, Limit) The same as the two-argument strcpy except that at most Limit characters are copied. strncat(Target_String_Var, Src_String, Limit) The same as the two argument strcat except that at most Limit characters are appended. strncmp(String_1,String_2, Limit) The same as the two-argument strcat except that at most Limit characters are compared. Functions for Manipulating Strings : Restricted
  • 39.
  • 40.
    Storing Multiple strings char name[10]; // Store 1 name of max 9 characters  char names[5][10]; // Store 5 names with each names upto 9 characters.
  • 41.
  • 42.
  • 43.
    Sorting of Strings Programmingwith Sikander | C Programming | Strings
  • 44.
    THANK YOU Programming withSikander | C Programming | Strings

Editor's Notes

  • #7 #include <stdio.h> int main() {   char s1[  ] = "SIKANDER";     char s2[10] = "sikander";     printf("Size of s1 = %ld \n",sizeof(s1));     printf("Size of s2 = %ld \n",sizeof(s2));     return 0; }
  • #19 #include <stdio.h> #define BUFFER_SIZE 50 int main (void) { int c; int nupper = 0; int nlower = 0; int ndigits = 0; char str[BUFFER_SIZE]; printf("Enter a string : "); fgets(str,BUFFER_SIZE,stdin); for(i = 0 ; (c = str[i]) != ‘\0’ ; i++) { if (isdigit (c)) ndigits++; else if (islower (c)) nlower++; else if (isupper (c)) nupper++; } printf ("No. of Digits = %d\n", ndigits); printf ("No. of Upper case = %d \n",nupper); printf ("No. of Lower case = %d\n ",nlower); return 0; }
  • #21 #include <stdio.h> #include <ctype.h> void toggle_case (char str[]) { int i; for(i = 0; str[i] != '\0' ; i++) { if (islower(str[i])) str[i] = toupper(str[i]); else if ( isupper(str[i]) ) str[i] = tolower(str[i]); } } int main() { char data[] = "Cranes Varsity"; printf("Original string : %s \n", data); toggle_case(data); printf("Toggled string : %s \n", data); return 0; }
  • #24 #include <stdio.h> #include <string.h> int main() {   char str[  ] = "SIKANDER";     printf("Size      = %ld \n",sizeof(str));     printf("Length    = %ld \n",strlen(str));     return 0; }
  • #25 #include <stdio.h> #include <string.h> int main() {   char str[10] = {'S','I','K','\0','A','N','D','E','R','\0'};     printf("Size      = %ld \n",sizeof(str));     printf("Length    = %ld \n",strlen(str));     return 0; }
  • #30 #include <stdio.h> #include <string.h> int main() {     char s1[10] = "SIKANDER";     char s2[10] = "SIKANDER";     int res = strcmp(s1, s2);     printf("res = %d \n", res);       return 0; }
  • #32 #include <stdio.h> #include <string.h> int main() {     char s1[10] ;     char s2[10] ;     printf("Enter first String : ");     scanf(" %s", s1);     printf("Enter second String : ");     scanf(" %s", s2);     int res = strcmp(s1, s2);     if(res == 0)         printf("Both Strings are equal \n");     else if(res > 0)         printf("%s > %s \n", s1, s2);     else         printf("%s < %s \n", s1, s2);       return 0; }
  • #33 #include <stdio.h> #include <string.h> int main() {   char firstName[] = "MOHAMMED";   char lastName[] = "SIKANDER";     char fullName[20] ;   strcpy(fullName, firstName);   strcat(fullName, lastName);     printf("FullName = %s \n",fullName);   return 0; }
  • #34 #include <stdio.h> #include <string.h> int main() {   char firstName[] = "MOHAMMED";   char lastName[] = "SIKANDER";     char fullName[20] ;   strcpy(fullName, firstName);   strcat(fullName, lastName);     printf("FullName = %s \n",fullName);   return 0; }
  • #37 #include <stdio.h> #include <string.h> int main() { char src[20] = "SIKANDER" char dest[20] = "ABCDEFGHIJKLMNOPQRS"; for(int i = 0 ; i < 20 ; i++) printf("%c",dest[i]); strcpy(dest , src ); //This will copy all characters from src to dest. for(int i = 0 ; i < 20 ; i++) printf("%c",dest[i]); return 0; }
  • #38 #include <stdio.h>#include <string.h>int main(){ char src[10] = "SIKANDER"; char dest[10] = "ABCDEFGHI"; strncpy(dest , src , 3); //This will copy all characters from src to dest. return 0;}
  • #39  #include <stdio.h> #include <string.h> int main() {   char  s1[10] = "4JN21EC105";   char  s2[10] = "4JN20CS045";           if(strncmp(s1 , s2 , 3) == 0)     printf("Same College \n");   else     printf("Different College \n");     return 0; }
  • #42 int main() {     char names[5][LENGTH] = {"SIKANDER","NIHAD",                            "BASAVARAJ", "ARUN","JITESH"};     for(int i = 0 ; i < n ; i++)     printf(" %s",names[i]); }
  • #43  #include <stdio.h> #define LENGTH  10 void printNames(char names[][LENGTH],int n) {   for(int i = 0 ; i < n ; i++)     printf(" %s",names[i]); } void sortStrings(char names[][LENGTH],int n) {   for(int p = 1 ; p < n  ; p++)     for(int c = 0 ; c < n - p ; c++)       if(strcmp(names[c], names[c + 1]) > 0)       {         char temp[LENGTH];         strcpy(temp, names[c]);         strcpy(names[c], names[c + 1]);         strcpy(names[c + 1], temp);       } } int main() {   char names[5][LENGTH] = {"SIKANDER","NIHAD","BASAVARAJ", "ARUN","JITESH"};   sortStrings(names, 5);   printNames(names , 5);       return 0; }