How to split and splice strings?

String segmentation and splicing are common operations in C language programming, especially when processing text data. In this article, I will explain in detail how to split and splice strings in C language, including methods of using standard library functions and manual manipulation of string arrays, as well as some practical application examples.

String splitting

String splitting is the process of splitting a string into multiple substrings, usually based on specific delimiters. In C language, there are several ways to achieve string splitting.

Use standard library function strtok()

The C standard library provides the strtok() function, which can be used to split a string into substrings. The prototype of the strtok() function is as follows:

char *strtok(char *str, const char *delim);

Among them, str is the string to be split, and delim is the string of delimiter. The strtok() function returns a pointer to the split substring until there are no more substrings to split, returning NULL.

Here is an example of using the strtok() function to split a string into words:

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

int main() {
    char str[] = "Hello,World,C Programming";
    char *token;

    // Use commas and spaces as separators
    token = strtok(str, ", ");

    while (token != NULL) {
        printf("%s\\
", token);
        token = strtok(NULL, ", ");
    }

    return 0;
}

In the above example, we first split the string str into words using the strtok() function, specifying comma and space as delimiters. We then use a loop to iterate through the split substrings until there are no more substrings to split.

Note that the strtok() function modifies the original string, replacing the delimiter with a null character ('\0'). So if you need to keep the original string, you can create a copy to split it.

Manually split string

Instead of using the strtok() function, you can split the string manually by searching for delimiters and splitting the string into substrings. This method is useful in situations where more precise control of the segmentation process is required.

Here is an example of manually splitting a string into substrings using a custom delimiter:

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

int main() {
    char str[] = "apple,banana,cherry,grape";
    char delimiter = ',';
    char *token;
    char *start = str;

    while ((token = strchr(start, delimiter)) != NULL) {
        *token = '\0'; // Replace delimiter with null character
        printf("%s\\
", start);
        start = token + 1; //Move the pointer to the beginning of the next substring
    }

    printf("%s\\
", start); // Print the last substring

    return 0;
}

In the above example, we use the strchr() function to find the separator character and replace it with the null character. We then move the pointer start to the start of the next substring and repeat the process until there are no more substrings.

String concatenation

String concatenation is the operation of combining multiple strings into a single string, and can be accomplished using a variety of methods.

Use standard library function strcat()

The C standard library provides the strcat() function, which can be used to splice two strings together. The prototype of the strcat() function is as follows:

char *strcat(char *dest, const char *src);

Where dest is the target string and src is the source string to be appended to the target string. The strcat() function appends the source string to the end of the destination string and returns a pointer to the destination string.

Here is an example using the strcat() function:

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

int main() {
    char dest[50] = "Hello, ";
    char src[] = "World!";

    strcat(dest, src);

    printf("Concatenated string: %s\\
", dest);

    return 0;
}

In the above example, we first initialize a destination string dest and then use the strcat() function to append the source string src to < At the end of code>dest, get the merged string.

It should be noted that the strcat() function modifies the target string and appends the content of the source string to the end of the target string.

Use string concatenation function

The C language does not provide a built-in string concatenation function, but you can use a custom function to implement string concatenation. Here is an example function that concatenates two strings together:

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

void custom_strcat(char *dest, const char *src) {
    while (*dest != '\0') {
        dest + + ;
    }

    while (*src != '\0') {
        *dest = *src;
        dest + + ;
        src++;
    }

    *dest = '\0'; // Add string terminator
}

int main() {
    char dest[50] = "Hello, ";
    char src[] = "World!";

    custom_strcat(dest, src);

    printf("Concatenated string: %s\\
", dest);

    return 0;
}

In the above example, we defined a custom custom_strcat() function that uses pointers to iterate over the target string and source string, copying the characters of the source string to the target string at the end of the string until the string terminator ('\0') is encountered.

This approach allows us to have more control over the string concatenation process without modifying the original string.

Practical application examples

1. CSV file analysis

When processing CSV (Comma Separated Values) files, it is often necessary to split each row of data into fields and concatenate the fields into strings. Here is a sample program that demonstrates how to read data from a CSV file and split and join it:

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

int main() {
    FILE *file = fopen("data.csv", "r");
    if (file == NULL) {
        perror("Failed to open file");
        return 1;
    }

    char line[256];
    while (fgets(line, sizeof(line), file) != NULL) {
        char *token;
        char *start = line;

        // Split row data and concatenate into strings
        while ((token = strchr(start, ',')) != NULL) {
            *token = '\0';
            printf("%s | ", start);
            start = token + 1;
        }
        printf("%s", start);
    }

    fclose(file);
    return 0;
}

In the above example, we opened a CSV file named data.csv, read each row of data, then split each row of data into fields using comma delimiters, and concatenated the fields is a string. This allows us to process the contents of the CSV file line by line.

2. String connector

Write a string concatenation program that accepts multiple strings entered by the user and concatenates them into a single string.

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

int main() {
    int n;
    printf("Enter the number of strings to concatenate: ");
    scanf("%d", & amp;n);

    char result[1000] = "";
    char input[100];

    for (int i = 0; i < n; i + + ) {
        printf("Enter string %d: ", i + 1);
        scanf("%s", input);
        strcat(result, input);
    }

    printf("Concatenated string: %s\\
", result);

    return 0;
}

This example program allows the user to enter multiple strings and concatenate them into a single string using the strcat() function.

Conclusion

String segmentation and concatenation are very common tasks in C programming, which is used to handle text data and string operations. You can use standard library functions such as strtok() and strcat() to accomplish these tasks, or you can create custom functions to perform string manipulation as needed. Mastering these techniques is very useful for processing and manipulating text data, and can play an important role in a variety of applications, including file parsing, string processing, and data concatenation. Hopefully, the detailed explanation provided in this article will help you better understand and apply string splitting and splicing operations.