String in C

In this tutorial, we will learn about the String in C. String is collection of character but in the background, the string is One-dimensional array is used to which terminates with null character ‘\0’. The null character at the end of the string tells the compiler about the end of the string

Initializing a String in C:

#include <stdio.h>

int main()
{
    char name[] = "Owlbuddy"; //Intilizing string
    char new_name[] = {'O','w','l','b','u','d','d','y'} ; //another way to Intilize string
    return 0;
}

Showing String output:

There is %s format specifier in C to show string output using printf function in c. Please check out the following example program to understand.

#include <stdio.h>

int main()
{
    char name[] = "Owlbuddy";
    printf("Hello %s",name);
    return 0;
}

Output:

Hello Owlbuddy

Taking String Input:

There are many situations when we need to get String input from user. For example, asking a user for his/her name. Please check out the following program to understand how we can take string input.

#include <stdio.h>
int main()
{
    char name[20];
    printf("Enter your name: ");
    scanf("%s", name);
    printf("Hello %s", name);
    return 0;
}

Output:

Enter your name: Owlbuddy                                                                                                     
Hello Owlbuddy   

In C there are many functions which makes it really easy to work with strings in C.

Function Description
strcpy(s1, s2); This function is used to copy string1 (s1) into string2 (s2).
strcat(s1, s2); This function is used to concatenate string2 (s2) at the end of the string1 (s1).
strlen(s1); This function is used to get the length of the string.
strcmp(s1, s2); This function return 0 in case both (s1 and s2) strings are same. retrun < 0 in case  s1<s2 and return > 0 if s1>s2.
strchr(s1, ch); This function return the pointer of the first occurrence of the character(ch) in given string(s1).
strstr(s1, s2); This function returns the pointer of the first occurrence of the string(s2) in a given string(s1).
Spread the love
Scroll to Top
×