简体   繁体   English

如何从带有空格的字符串中连接 C 中的字符?

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

I'm trying to concatenate characters in C, but no success.我正在尝试连接 C 中的字符,但没有成功。 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主要字符串: hello world wide
New string: hww新字符串: 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.我在互联网上进行了研究,发现strcpystrcat函数很有用,但即使使用它们我也没有成功。 In the same way, I tried to do something like result += string[i + 1] and it doesn't work.同样,我尝试执行类似result += string[i + 1]的操作,但它不起作用。

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:如果你想将结果连接成一个字符串,'result' 应该是一个 char 数组:

//...

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:您还可以使用“strtok_r”来简化事情,实现它的一种方法是这样的:

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.请注意,“结果”数组的大小是任意的,仅适用于 3 个或更少的单词。 You can create a similar for loop to count the number of spaces in the string to find out how many words there are.您可以创建一个类似的 for 循环来计算字符串中的空格数以找出有多少单词。

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程序 output 是

sip

You cannot concatenate strings or characters with the + or += operators in C.您不能使用 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.您必须定义一个足够大的char数组来接收新字符串并一次将适当的字符存储到其中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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