C Tutorial C References

C - Strings



In C language, a string is an array of characters terminated with a null character \0. When a compiler encounters a string without null character \0, it appends the null character \0 at the end by default.

Create a C-String

There are number of ways to declare a c-string. See the syntax below:

Syntax

char str[] = "HELLO";
char str[] = {'H', 'E', 'L', 'L', 'O', '\0'};

char str[6] = "hello";
char str[6] = {'H', 'E', 'L', 'L', 'O', '\0'};

char str[50] = "hello";
char str[50] = {'H', 'E', 'L', 'L', 'O', '\0'};

Example:

In the example below, illustrates how a strings is created in the C language.

#include <stdio.h>
 
int main (){
  char str1[] = "Hello World!.";
  char str2[] = {'H', 'E', 'L', 'L', 'O', '\0'};

  printf("%s\n", str1);
  printf("%s\n", str2);
  return 0;
}

The output of the above code will be:

Hello World!.
HELLO

Access character of a String

A character of a string can be accessed with it's index number. In C, index number starts with 0 in forward direction. The figure below describes the indexing concept of a string.

String Indexing:

C String Indexing

The example below describes how to access character of a string using its index number.

#include <stdio.h>
 
int main (){
  char str[] = "HELLO";

  printf("%c\n", str[1]);
  printf("%c\n", str[4]);
  return 0;
}

The output of the above code will be:

E
O   

Special characters in a string array

The backslash \ escape character is used to convert special character like single quote, double quote, new line, etc. into the string character. The below mentioned table describes special characters in C language:

Escape CharacterResultExample
\' ' "\'C\' Language" is converted into: 'C' Language
\" " "\"Hello\"" is converted into: "Hello"
\\ \ "A\\C" is converted into: A\C
\n new line "Hello\nJohn" is converted into:
Hello
John
\t Tab "Hello\tMarry" is converted into: Hello    Marry

String Functions

C language has number of string functions. To use them, we have to include string.h in the program. Here, few very common string functions are discussed.

  • strlen(): returns the number of characters in the given string.
  • strcat(): returns the number of characters in the given string.

String Length

The strlen() function is used to find out total number of characters in the string array.

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

int main (){
  char str[] = "HELLO";

  printf("%li\n", strlen(str));
  return 0;
}

The output of the above code will be:

5 

String Concatenation

Two string arrays can be joined using strcat() function.

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

int main (){
  char str1[] = "Hello ";
  char str2[] = "World!.";

  printf("%s\n", strcat(str1, str2));
  return 0;
}

The output of the above code will be:

Hello World!.