Skip to content

String manipulation in C

String manipulation in C involves performing various operations on strings, such as copying, concatenating, comparing, searching, tokenizing, and modifying strings. These operations are typically achieved using string manipulation functions provided by the standard library <string.h>. Let’s discuss some common string manipulation tasks and how they are performed in C:

1. Copying Strings:

You can copy one string to another using the strcpy() function:

#include <stdio.h>

#include <string.h>

int main() {

    char source[] = “Hello”;

    char destination[10];

    strcpy(destination, source);

    printf(“Copied string: %s\n”, destination); // Output: Hello

    return 0;

}

2. Concatenating Strings:

You can concatenate two strings using the strcat() function:

#include <stdio.h>

#include <string.h>

int main() {

    char str1[20] = “Hello”;

    char str2[] = ” World!”;

    strcat(str1, str2);

    printf(“Concatenated string: %s\n”, str1); // Output: Hello World!

    return 0;

}

3. Comparing Strings:

You can compare two strings using the strcmp() function:

#include <stdio.h>

#include <string.h>

int main() {

    char str1[] = “Hello”;

    char str2[] = “World”;

    int result = strcmp(str1, str2);

    if (result == 0) {

        printf(“Strings are equal\n”);

    } else if (result < 0) {

        printf(“str1 is less than str2\n”);

    } else {

        printf(“str1 is greater than str2\n”);

    }

    return 0;

}

4. Searching Characters in Strings:

You can search for a character in a string using the strchr() function:

#include <stdio.h>

#include <string.h>

int main() {

    char str[] = “Hello, World!”;

    char *ptr = strchr(str, ‘W’);

    if (ptr != NULL) {

printf(“Character found at position: %ld\n”, ptr – str); // Output: Character found at position: 7

    }

 else

{

        printf(“Character not found\n”);

    }

    return 0;

}

5. Searching Substrings in Strings:

You can search for a substring in a string using the strstr() function:

#include <stdio.h>

#include <string.h>

int main() {

    char str[] = “Hello, World!”;

    char *ptr = strstr(str, “World”);

    if (ptr != NULL) {

        printf(“Substring found at position: %ld\n”, ptr – str); // Output: Substring found at position: 7

    } else {

        printf(“Substring not found\n”);

    }

    return 0;

}

6. Tokenizing Strings:

You can tokenize a string into smaller strings (tokens) based on delimiters using the strtok() function:

#include <stdio.h>

#include <string.h>

int main() {

    char str[] = “Hello,World,How,Are,You”;

    char *token = strtok(str, “,”);

    while (token != NULL) {

        printf(“%s\n”, token);

        token = strtok(NULL, “,”);

    }

    return 0;

}

These are some common string manipulation tasks in C. By using the appropriate string manipulation functions, you can efficiently work with strings in your C programs.