简体   繁体   中英

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.

If you want to concatenate the result in a string, 'result' should be a char array:

//...

char result[4];
int currentWord = 0;

for (i = 0; i < stringLength; i++)
{
    if (string[i] == ' ')
    {
        result[currentWord] = string[i + 1];
        currentWord++;
    }
}

Another problem with your code is that it wont read the first word, because it does not have a space before. One way to fix this is to assign the first of the string to the first element of the word:

char result[4];
if (string[0] != ' ') result[0] = string[0];
int currentWord = 1;

You can also use 'strtok_r' to simplify things, one way to implement it is like this:

char *saveptr;
result[0] = strtok_r(string, " ", &saveptr)[0];
for (i = 1; i < 3; i++) // 3 is the word count
{
    result[i] = strtok_r(NULL, " ", &saveptr)[0];
}

Note that the size of the 'result' array is arbitrary and will only work with 3 or less words. You can create a similar for loop to count the number of spaces in the string to find out how many words there are.

If you need to change the source array such a way that it would contain only first characters of words in the stored string then the program can look the following way.

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

int main( void ) 
{
    char s[] = "str ing placeholder";
    const char *delim = " \t";
    
    for ( char *p = s + strspn( s, delim ), *q = p; *q; p += strspn( p, delim ) )
    {
        *q++ = *p;
        p += strcspn( p, delim );
    }

    puts( s );
    
    return 0;
}

The program output is

sip

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM