× back String String Variables String Initialization Programs String library function
Next Topic → ← Previous Topic

String

String Constant or String Literal

                
"V"
"Taj Mahal"
"2345"
"" (Null string, contains only '\0')
"My age is %d and height is %f\n" (Control string used in printf)
                
            

String Variables

                
char str[] = {'N', 'e', 'w', ' ', 'Y', 'o', 'r', 'k', '\0'};
                
            

We may also initialize it as-

                
char str[] = "New York";
                
            

This initialization is same as the previous one and in this case the compiler automatically inserts the null character at the end. Note that here the string constant does not represent an address. The array str will be stored in memory as ↓
Here we have not specified the size of the array, but if we specify it then we should take care that array should be large enough to hold all the characters including the null character.

Program to print characters of a string and address of each character

                   
#include <stdio.h>
int main()
{
    char str[] = "India";
    int i;
    for (i = 0; str[i] != '\0'; i++)
    {
        printf("Character = %d\t", str[i]);
        printf("Address = %u\n", &str[i]);
    }
    return 0;
}
                   
               

Output ↓

                
Character = 73  Address = 3134707238
Character = 110 Address = 3134707239
Character = 100 Address = 3134707240
Character = 105 Address = 3134707241
Character = 97  Address = 3134707242
                
            

Initialization of string

Runtime initializaiton

  • scanf("%s", str) can be used but it there is white space (space bar, tab, etc.) in between string then only words till first white space are taken because whitespace terminate the scanf() function.
  • gets() function can also be used which can take white spaces.
  • fgets() function is used and it is supported in linux OS.

Program to intialize string variable runtime using scanf() function

                           
#include <stdio.h>
int main()
{
    char str[30];
    printf("Enter your string : ");
    scanf("%s", str);
    printf("\nYour entered string is = %s", str);
    return 0;
}
                           
                       

Output ↓

                        
    Enter your string : Hi my name is 
    
    Your entered string is = Hi%
                        
                    

Only "Hi" is stored because after that there was a whitespace.

Program to intialize string variable runtime using gets() function.

                           
#include <stdio.h>
int main()
{
    char str[30];
    printf("Enter your string : ");
    gets(str);
    printf("\nYour entered string is = %s", str);
    return 0;
}
                           
                       

Output ↓

                        
Enter your string : Hi my name is 

Your entered string is = Hi my name is
                        
                    

Program to intialize string variable runtime using fgets() function.

                           
#include <stdio.h>
int main()
{
    char str[30];
    printf("Enter your string : ");
    fgets(str, 30, stdin);
    printf("\nYour entered string is = %s", str);
    return 0;
}
                           
                       

Output ↓

                        
Enter your string : Hello my name is

Your entered string is = Hello my name is
                        
                    

Compile time intialization

Programs

Program to convert string to opposite case (if upper then convert it to lower and vice versa)
ACSII code for 'A' to 'Z' → 65 - 90
ACSII code for 'a' to 'z' → 97 - 122

                       
#include <stdio.h>
#include <string.h>
int main()
{
    int i;
    char str[30];
    printf("Enter your string : ");
    fgets(str, 30, stdin);
    for (i = 0; i < strlen(str); i++)
    {
        if (str[i] >= 65 && str[i] <= 90)
            str[i] = str[i] + 32;
        else
            str[i] = str[i] - 32;
    }
    printf("The converted string is = %s", str);
    return 0;
}
                       
                   

Program to reverse any string without using predefind function.

                       
#include <stdio.h>
#include <string.h>
int main()
{
    int i, l;
    char str[30];
    printf("Enter your string : ");
    fgets(str, 30, stdin);
    l = strlen(str);
    for (i = 0; i < l / 2; i++)
    {
        char temp = str[i];
        str[i] = str[l - i - 1];
        str[l - i - 1] = temp;
    }
    printf("Revese of string is = %s", str);
    return 0;
}
                       
                   

Second method ↓

                       
#include <stdio.h>
#include <string.h>
int main()
{
    char x[12];
    char temp;
    int i, l;

    printf("Enter the string =");
    fgets(x, 12, stdin);
    l = strlen(x);
    for (i = 0; i < l / 2; i++)
    {
        temp = x[i];
        x[i] = x[l - i - 1];
        x[l - i - 1] = temp;
    }
    printf("%s", x);

    return 0;
}
                       
                   

Program to check whether a string is palindrome or not

                       
#include <stdio.h>
#include <string.h>
int main()
{
    int i, l, flag = 1;
    char str[30];
    printf("Enter your string : ");
    fgets(str, 30, stdin);
    l = strlen(str) - 1;
    for (i = 0; i < l / 2; i++)
    {
        if (str[i] != str[l - i - 1])
        {
            flag = 0;
            break;
        }
    }
    if (flag)
        printf("The given string is a palindrome");
    else
        printf("The given string is not a palindrome");
    return 0;
}
                       
                   

Second method ↓

                       
#include <stdio.h>
#include <string.h>
int main()
{
    int i, l, flag = 1;
    char str[30];
    printf("Enter your string : ");
    fgets(str, 30, stdin);
    int high = 0, low = strlen(str) - 1;
    while (low < high)
    {
        if (str[low] != str[high])
        {
            flag = 0;
            break;
        }
        low++;
        high--;
    }
    if (flag)
        printf("The given string is a palindrome");
    else
        printf("The given string is not a palindrome");
    return 0;
}
                       
                   

String Library Function

strlen()

  • This function returns the length of the string i.e. the number of characters in the string excluding the terminating null character. It accepts single argument, which is pointer to the first character of the string.
  • For example strlen("suresh") returns the values 6. Similarly if s1 is an array that contains the name "deepali" then strlen(s1) returns the value 7.
                       
#include<stdio.h>
#include<string.h>
int main()
{
    char str[20];
    int length;
    printf("Enter the string : ");
    scanf("%s", str);
    length = strlen(str);
    printf("Length of the string is : %d", length);
}
/*
    output : 
    Enter the string : CinDepth
    Length of string is : 8
*/
                       
                   

strcmp()

  • This function is used for comparison of two strings.
  • If the two strings match, strcmp() returns value 0, otherwise it returns a non-zero value.
  • This function compares the strings character by character. The comparison stops wen either the end of string is reached of the corresponding characters in the two strings are not same. The non-zero value returned on mismatch is the difference of the ASCII value of the non-matching characters of the two strings.
  • Strcmpe(s1, s2) returns a value -
    < 0 when s1 < s2
    = 0 when s1 = = s2
    > 0 when s1 > s2

Program to understand the work of strcmp() function ↓

                       
#include<stdio.h>
#include<string.h>
int main()
{
    char str1[10], str2[10];
    printf("Enter the first string : ");
    scanf("%s", str1);
    printf("Enter the second string : ");
    scanf("%s", str2);
    if(strcmp(str1, str2) == 0)
        printf("Strings are same");
    else 
        printf("Strings are not same");
}
/*
output : 
Enter the first string : Bangalore
Enter the second string : Mangolore
Strings are not same
*/
                       
                   

strcpy()

  • This function is used for copying one string to another string.
  • strcpy(str1, str2) copies str2 to str1. Here str2 is the source string and str1 is destination string.
  • If str2 = "suresh" then this function copies "suresh" into str1. This function takes pointers to two strings as arguments and returns the pointer to first string.

Program to understand the work of the strcpy() function

                       
#include<stdio.h>
#include<string.h>
int main()
{
    char str1[10], str2[10];
    printf("Enter the first string : ");
    scanf("%s", str1);
    printf("Enter the second string : ");
    scanf("%s", str2);
    strcpy(str1, str2);
    printf("First string : %s \t\t Second string : %s\n", str1, str2);
    strcpy(str1, "Delhi");
    strcpy(str2, "Calcutta");
    printf("First string : %s \t\t Second string : %s\n", str1, str2);
    return 0;
}
/*
output:
Enter the first string : Henry
Enter the second string : Ford
First string : Ford              Second string : Ford
First string : Delhi             Second string : Calcutta
*/
                       
                   

strcat()

  • This function is used for concatenation of two strings. If first string is "King" and second string is "size" then after using this function the first string becomes "Kingsize".
  • The null character from the fisrt string is removed, and the second string is added at the end of first string. The second string remains unaffected.

Program to understand the work of strcat() function

                       
#include <stdio.h>
#include <string.h>

int main() {
    char str1[100], str2[100];

    printf("Enter the first string: ");
    scanf("%99s", str1);

    printf("Enter the second string: ");
    scanf("%99s", str2);

    strcat(str1, str2);

    printf("Concatenated string: %s\n", str1);

    return 0;
}

                       
                   

strrev()

  • This function reverse the string in which it is applied.
  • This function is not built-in in string.h header file.

strupr()

  • This function converts the lower case letters to upper case in a string.
  • This function is not built-in in string.h header file.

strlwr()

  • This function converts the upper case letters to lower case in a string.
  • This function is not built-in in string.h header file.

Passing string to function

                   
#include <stdio.h>
#include <string.h>

void modifyString(char* str) {
    // Appending " (Modified)" to the string
    strcat(str, " Happy Coding");
}

int main() {
    char message[50] = "Hello, World!";
    printf("Before modification: %s\n", message);
    
    modifyString(message);
    
    printf("After modification: %s\n", message);
    
    return 0;
}
                   
               

Output ↓

                
Before modification: Hello, World!
After modification: Hello, World! Happy Coding