C Programs Tutorials | IT Developer
IT Developer

C Programming - C Strings



Share with a Friend

C Programming - C Strings

C Strings

In C, strings are arrays of characters that are terminated by a null character ('\0'). They are used to store and manipulate text data.

  1. Declaring and Initializing Strings

Declaration:

Strings in C are declared as character arrays:

C

char str[20]; // Can hold up to 19 characters and 1 null character

Initialization:

There are two main ways to initialize a string:

  1. Character Array:

C

char str[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

  1. String Literal:

C

char str[] = "Hello";

  1. Accessing String Characters

Individual characters in a string can be accessed using array indexing:

C

char str[] = "Hello";

printf("%c", str[0]); // Output: H

  1. Input and Output of Strings

Reading a String:

Using scanf():

C

char name[50];

printf("Enter your name: ");

scanf("%s", name); // Reads input until a space or newline

  • Limitation: scanf() cannot read strings with spaces. For that, use gets() (deprecated) or fgets().

Output a String:

Using printf():

C

char str[] = "Hello, World!";

printf("%s", str);

  1. Common String Functions

C provides a library <string.h> with many functions for string manipulation.

(a) String Length:

To find the length of a string:

C

#include <string.h>

char str[] = "Hello";

int len = strlen(str); // Returns 5

(b) String Copy:

To copy one string into another:

C

#include <string.h>

char src[] = "Hello";

char dest[10];

strcpy(dest, src); // Copies "Hello" into dest

(c) String Concatenation:

To concatenate (join) two strings:

C

#include <string.h>

char str1[20] = "Hello, ";

char str2[] = "World!";

strcat(str1, str2); // str1 becomes "Hello, World!"

(d) String Comparison:

To compare two strings:

C

#include <string.h>

char str1[] = "Hello";

char str2[] = "World";

int result = strcmp(str1, str2); // Returns 0 if equal, <0 if str1 < str2, >0 if str1 > str2

(e) Substring Search:

To find a substring within a string:

C

#include <string.h>

char str[] = "Hello, World!";

char *substr = strstr(str, "World"); // Returns pointer to "World"

(f) Character Search:

To find a character in a string:

C

#include <string.h>

char str[] = "Hello";

char *ch = strchr(str, 'e'); // Returns pointer to 'e'

  1. String Operations Without Library Functions

C programmers can implement string operations manually using loops.

(a) String Length:

C

int string_length(char str[]) {

    int i = 0;

    while (str[i] != '\0') {

        i++;

    }

    return i;

}

(b) String Copy:

C

void string_copy(char dest[], char src[]) {

    int i = 0;

    while (src[i] != '\0') {

        dest[i] = src[i];

        i++;

    }

    dest[i] = '\0'; // Null-terminate the destination string

}

(c) String Concatenation:

C

void string_concatenate(char str1[], char str2[]) {

    int i = 0, j = 0;

    while (str1[i] != '\0') {

        i++;

    }

    while (str2[j] != '\0') {

        str1[i] = str2[j];

        i++;

        j++;

    }

    str1[i] = '\0';

}

  1. Dynamic String Allocation

Strings can be dynamically allocated using malloc() or calloc().

Example:

C

#include <stdio.h>

#include <stdlib.h>

int main() {

    char *str = (char *)malloc(20 * sizeof(char)); // Allocate memory for 20 characters

    if (str == NULL) {

        printf("Memory allocation failed!");

        return 1;

    }

    strcpy(str, "Hello, Dynamic!");

    printf("%s\n", str);

    free(str); // Free allocated memory

    return 0;

}

  1. Common Mistakes with Strings
  1. Uninitialized Strings:

C

char str[10];

printf("%s", str); // Undefined behavior

  1. Buffer Overflow:

C

char str[5];

strcpy(str, "Hello, World!"); // Exceeds allocated memory

  1. Forgetting the Null Character:

C

char str[5] = {'H', 'e', 'l', 'l', 'o'}; // No null character, not a proper string

  1. Advantages of Strings in C
  • Simple and lightweight.
  • Direct access to individual characters.
  • Extensive library support in <string.h>.
  1. Limitations of Strings in C
  • Fixed-size character arrays limit flexibility.
  • Manual memory management can lead to errors like buffer overflow or memory leaks.
  • No built-in string data type, unlike modern languages.
  1. Example Program

C

#include <stdio.h>

#include <string.h>

int main() {

    char name[50];

    char greeting[100] = "Hello, ";

    printf("Enter your name: ");

    scanf("%s", name);

    strcat(greeting, name); // Concatenate name to greeting

    strcat(greeting, "! Welcome to C programming.");

    printf("%s\n", greeting); // Display final greeting

    return 0;

}

Output:

Enter your name: Alice

Hello, Alice! Welcome to C programming.