Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Introduction to Strings in C

What is a String?

In C programming, a string is a sequence of characters terminated by a null character ('\0'). Strings are used to represent text. In C, strings are arrays of characters.

Declaring and Initializing Strings

Strings in C can be declared and initialized in several ways:

char str1[] = "Hello";
char str2[6] = "World";
char str3[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

In the first line, the size of the array is determined automatically by the compiler. In the second line, the size of the array is explicitly specified. In the third line, the string is initialized character by character.

Accessing Characters in a String

You can access individual characters in a string using the array index notation:

char str[] = "Hello";
printf("%c", str[1]);  // Outputs 'e'

String Input and Output

The scanf function can be used to read a string, and the printf function can be used to print a string:

char str[50];
printf("Enter a string: ");
scanf("%s", str);
printf("You entered: %s", str);

Note that scanf stops reading input at the first whitespace character.

String Functions

The C standard library provides several functions for handling strings. Some commonly used functions are:

  • strlen - returns the length of a string
  • strcpy - copies one string to another
  • strcat - concatenates two strings
  • strcmp - compares two strings
#include <string.h>

char str1[20] = "Hello";
char str2[20] = "World";
char str3[40];

strcpy(str3, str1);       // Copies "Hello" to str3
strcat(str3, " ");        // Concatenates a space to str3
strcat(str3, str2);       // Concatenates "World" to str3

int len = strlen(str3);   // Returns the length of str3

int cmp = strcmp(str1, str2); // Compares str1 and str2

Example Program

Below is an example program that demonstrates the use of various string functions:

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

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

    strcpy(str3, str1);
    strcat(str3, " ");
    strcat(str3, str2);

    printf("Combined string: %s\n", str3);
    printf("Length of combined string: %lu\n", strlen(str3));

    int cmp = strcmp(str1, str2);
    if(cmp == 0) {
        printf("Strings are equal\n");
    } else if(cmp > 0) {
        printf("str1 is greater than str2\n");
    } else {
        printf("str1 is less than str2\n");
    }

    return 0;
}