Skip to main content

Introduction to Strings in C

Introduction

In C programming, a string is a sequence of characters. Unlike other programming languages, C does not have a specific 'string' data type. Instead, strings are represented as an array of characters, which ends with a special character, the null character (\0).

Declaration of Strings

Strings in C are declared much like arrays. Here is a simple example of how to declare a string:

char name[10];

In the above example, name is a string which can hold up to 10 characters. It's important to note that one character space is reserved for the null character (\0) at the end of the string.

Initialization of Strings

Strings can be initialized at the time of declaration. Here is an example:

char name[] = "John Doe";

In the above example, the string name is initialized with the value "John Doe". You don't need to specify the size of the array when you declare and initialize it at the same time. The compiler automatically calculates the size.

Accessing String Elements

Just like arrays, you can access individual elements of a string using their index number. Remember, the index number starts from 0. Here is an example:

char name[] = "John Doe";
printf("%c\n", name[0]); // Prints 'J'

In the above example, name[0] gives the first character of the string, which is 'J'.

String Functions

C provides a rich set of built-in string functions in the string.h library. Some of the common functions include:

  • strlen(): This function returns the length of the string.
  • strcpy(): This function copies the string to another string.
  • strcat(): This function concatenates two strings.
  • strcmp(): This function compares two strings.

Here is an example of how to use these functions:

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

int main() {
char str1[10] = "Hello";
char str2[10] = "World";
char str3[10];
int len;

// copy str1 into str3
strcpy(str3, str1);
printf("strcpy(str3, str1): %s\n", str3);

// concatenates str1 and str2
strcat(str1, str2);
printf("strcat(str1, str2): %s\n", str1);

// total length of str1 after concatenation
len = strlen(str1);
printf("strlen(str1) : %d\n", len);

return 0;
}

Conclusion

Understanding strings in C is fundamental as they are used in almost every C program. They are a powerful tool for handling and manipulating text. Practice using strings, string functions, and become comfortable with them to improve your C programming skills.