Strings in C [Explained A to Z]

In this article, we have explained the basics of String in C Programming Language along with basic operations like declaration, initialization, readingm displaying a string, basic handling and much more.

Table of content:

  1. Basics of String
  2. Declaration of Strings
  3. Initialization of Strings
  4. Reading a string
  5. Displaying Strings
  6. Header File: string.h
  7. C String Handling
  8. Converting a String to a Number
  9. Summary

Basics of String

String is defined as one-dimensional array of characters terminated with a null character '\0'.
Unlike character, string is represented using double quotes.

char ch='a';
char str[10]="OpenGenus";

Declaration of Strings

String is not directly supported in C language as a data type so it is declared under char data type. An array with char as data type declares a string in C.

Syntax :

char string_name[size];

The size of array must be defined while declaring the string variable because it is used to calculate the number of characters the string variable will store. The indexing will start from 0 hence it will store characters from 0 to [size-1] position.

Consider the following example,

char str[10]; //declaration of string variable

The above example represents a string variable named as str with an array size of 10 characters. It means that str is capable of holding 10 characters atmost. The indexing will start from 0 and end at 9th position. The C compiler automatically adds a Null character '\0' to the character array.

Indexing_of_strings

Initialization of Strings

Let us consider the following examples to understand the initialization of the strings in a much better way.

char str1[]="OpenGenus";
char str2[10]="OpenGenus";
char str3[]={'O','p','e','n','G','e','n','u','s','\0'}
char str4[10]={'O','p','e','n','G','e','n','u','s','\0'}
  1. str1 shows that C allows us to initialize a string variable without declaring the size of character array.
  2. str2 is an example of classic way of declaring a string variable.
  3. In str3 and str4, Null character must be added explicitly and characters enclosed in single quotes.

Please note that there is an extra terminating character which is the Null character '\0' which indicates the termination of string and hence differs strings from normal character arrays.

The name of string variable acts as a pointer since it is an array.

Reading a string

scanf() : We use the "%s" format specifier without using the "&" to access the variable address because an array name acts as a pointer.

For example,

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

Input :

Enter your name : James

Output :

Hello James!

Unlike arrays, we do not need to print a string, character by character.

The problem with scanf() function is that it never reads the entire string once it encounters a whitespace or a new line.

For example,

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

Input :

Enter your full name : James Mathew

Output :

Hello James!

This problem can be solved by using gets() function. Unlike scanf(), gets() can read strings even with whitespaces. It will be terminated when it encounters a new line, i.e., when enter is pressed.

For example,

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

Input :

Enter your full name : James Mathew

Output :

Hello James Mathew!

warning : the 'gets' function is dangerous and should not be used.

Sometimes the compiler gives the above warning, so safer alternative to gets() is fgets().

It reads the line from the specified stream and saves it to the thread indicated by str. It terminates when new line character is encountered or maximum limit of character array is reached.

Syntax :

char *fgets(char *str, int n, FILE *stream)

str : Pointer to an array of chars where the string read is copied.
n : Maximum number of characters to be copied into str
(including the terminating null-character).
*stream : Pointer to a FILE object that identifies an input stream.
stdin can be used as argument to read from the standard input.

Consider the following example,

#include <stdio.h>
int main()
{
    char str[30];
    printf("Enter your full name : ");
    fgets(str,30,stdin);
    printf("Hello %s!", str);
    return 0;
}

Input :

Enter your full name : James Mathew

Output :

Hello James Mathew
!

Displaying Strings

The standard printf() function can be used with format specifier %s to print or display the string in C.

printf("%s ",str);

Like gets() and fgets() are functions used to read strings, we can use their opposites like puts() and fputs() to display the strings.
puts() is used to print string in C. It is preferred over printf() because it has generally simpler syntax than printf().

#include <stdio.h>
int main()
{
    char str[30];
    printf("Enter your full name : ");
    gets(str);
    printf("Hello ");
    puts(str);
    printf("!");
    return 0;
}

Input :

Enter your full name : James Mathew

Output :

Hello James Mathew
!

Note that puts() moves the cursor to the next line. If you want to avoid that, then use fputs().

fputs(str, stdout);

Consider the following example,

#include <stdio.h>
int main()
{
    char str[30];
    printf("Enter your full name : ");
    gets(str);
    printf("Hello ");
    fputs(str, stdout);
    printf("!");
    return 0;
}

Input :

Enter your full name : James Mathew

Output :

Hello James Mathew!

Header File: string.h

Under the C Standard Library, string.h is the header file required to use various string functions, which are used to manipulate the strings within a program. Such functions are called string handlers.

C String Handling

Let us now discuss some of the in-built functions under string.h

  • strlen(str) : Compute the length of the string. It doesn't count Null character '\0'.
  • strcat(str1,str2) : Appends str2 at the end of str1
  • strcmp(str1,str2) : Compares the two strings
    • Returns -ve value if str1 < str2
    • Returns +ve value if str1 > str2
    • Returns 0 value if str1=str2
  • strcpy(str1,str2) : Copies second string into first
  • strstr(str1,str2) : Checks whether str2 is present in str1 or not.
    • On success, strstr returns a pointer to the element in str1 where str2 begins (points to str2 in str1).
    • On error (if str2 does not occur in str1), strstr returns null.
  • strtok(str,delimiter) : tokenizes/parses the given string using delimiter.
  • strncmp(str1,str2,n) : It compares the first n characters of str1 and str2.
    • returns 0 if the first n characters of str1 is equal to the first n characters of str2.
    • returns -ve value if str1 < str2
    • returns +ve value if str1 > str2
  • strncpy(str1,str2,n) : Copies the first n characters of str2 to str1.
  • strncat(str1,str2,n) : Concatenates first n characters of str2 to the end of str1 and returns a pointer to str1.

Let us consider the following examples to understand how to use these string function.

#include <stdio.h>
#include <string.h>
int main()
{
    //example of strlen
    char str[]="Programming";
    int l=strlen(str);                      
    printf("Length of the string : %d\n",l);
    
    //example of strcat
    char str1[10]="Open", str2[10]="Genus";     
    printf("\nConcatenated String : %s\n\n",strcat(str1,str2));
    
    //exmple of strcmp
    char s1[]="SAM", s2[]="Sam";
    int val=strcmp(s1,s2);
    if(val==0) printf("s1 and s2 are equal.");
    else if(val>0) printf("s1 is greater than s2.");
    else printf("s2 is greater than s1.");
    
    //example of strcpy
    printf("\n\nCopied string : %s ",strcpy(str1,str2));
    printf("\nstr1=%s , str2=%s\n\n",str1,str2); //value of str1 changes
    
    //example of strstr
    char string[55] ="This is a test string";
    char *p = strstr(string,"test");
    if(p)
    {
        printf("string found\n");
        printf("String \"test\" in \"%s\" is \"%s\"\n\n" ,string, p);
    }
    else    printf("string not found\n" );
    
    //example of strtok
    char s[] = "Problem_Solving_in_C";
    char* token = strtok(s, "_");   //Returns first token
    while (token != NULL) //Keep printing tokens while one of the delimiters present in s[].
    {
        printf("%s\n", token); 
        token = strtok(NULL, "_");
    }
    return 0;
}

Output :

Length of the string : 11
    
Concatenated String : OpenGenus

s2 is greater than s1.

Copied string : Genus 
str1=Genus , str2=Genus
    
string found
String "test" in "This is a test string" is "test string"

Problem
Solving
in
c

Converting a String to a Number

We can convert a string of numeric characters to a numeric value to prevent a run-time error. The C standard library header file stdlib.h contains the following functions for converting a string to a number:

  • atof() Converts string to float
  • atoi() Converts string to int
  • atol() Converts string to long
  • itoa() Converts int to string
  • ltoa() Converts long to string

Typecasting functions in C language performs data type conversion from one type to another.

atoi : ASCII to Integer
Converts string of number into integer.
Example,

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int num=atoi("98");
    printf("Marks : %d",num);
}

Output:

Marks : 98

Summary

  • String is simple array of characters terminated by a Null character '\0';
  • It is enclosed within double quotes.
  • A string must be declared or initialized before using in the program.
  • There are different functions to input or output strings with different features.
  • String handler functions are used under the string.h header file.
  • We can convert string to number through the atoi(), atof() and atol() which are very useful for coding and decoding processes. These functions are used under the stdlib.h header file.

With this article at OpenGenus, you must have a strong idea of string in C Programming Language.