Search code examples
cc-strings

How to concatenate characters in C from a string with spaces?


I'm trying to concatenate characters in C, but no success. The problem is to take a string, check if there is space in that string, and create a new string from the letters that come after the space in that main string.

Example:

Main string: hello world wide
New string: hww

I have no idea how to concatenate. I researched on the internet, I saw that the strcpy and strcat functions can be useful, but even using them I am not successful. In the same way, I tried to do something like result += string[i + 1] and it doesn't work.

Source code

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

int main()
{
    char string[] = "str ing placeholder";
    int stringLength = strlen(string);
    int i;
    char result;
    
    for (i = 0; i < stringLength; i++)
    {
        if (string[i] == ' ')
        {
            printf("Found space at the index: %d\n", i);
            result = string[i + 1];
            printf("\nNext char: %c\n", result);
        }
    }
    return 0;
}

Hope someone can guide me. I don't think my program logic is wrong, all I need is to take the first character of the string and each character that follows the space of a string and concatenate into a new string, then present this newly formed string.


Solution

  • You cannot concatenate strings or characters with the + or += operators in C. You must define an array of char large enough to receive the new string and store the appropriate characters into it one at a time.

    You probably want to copy the initial of each word to a buffer instead of every character that follows a space.

    Here is a modified version:

    #include <stdio.h>
    
    int main() {
        const char text[] = "Hello wild world!";
        char initials[sizeof text];  // array for the new string
        int i, j;
        char last = ' ';  // pretend the beginning of the string follows a space
    
        // iterate over the main string, stopping at the null terminator
        for (i = j = 0; text[i] != '\0'; i++) {
             // if the character is not a space but follows one
             if (text[i] != ' ' && last == ' ') {
                 // append the initial to the new string
                 initials[j++] = text[i];
             }
             last = text[i]; // update the last character
        }
        initials[j] = '\0';  // set the null terminator in the new string.
        printf("%s\n", initials);  // output will be Hww
        return 0;
    }