【问题标题】:How to concatenate characters in C from a string with spaces?如何从带有空格的字符串中连接C中的字符?
【发布时间】:2022-01-11 22:55:54
【问题描述】:

我正在尝试连接 C 中的字符,但没有成功。问题是获取一个字符串,检查该字符串中是否有空格,然后根据该主字符串中空格后面的字母创建一个新字符串。

例子:

主字符串:hello world wide
新字符串:hww

我不知道如何连接。我在互联网上进行了研究,发现strcpystrcat 函数很有用,但即使使用它们我也没有成功。同样的,我尝试做类似result += string[i + 1]的事情,但它不起作用。

源代码

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

希望有人可以指导我。我不认为我的程序逻辑有问题,我只需要将字符串的第一个字符和字符串空格后面的每个字符连接成一个新字符串,然后呈现这个新形成的字符串。

【问题讨论】:

  • 你的逻辑确实不正确。如果您有多个连续的空格,则此代码无法干净地处理。
  • newstring[index++] = oldstring[firstletter]; 终于以newstring[index] = '\0'; 结束
  • @Shi Nha 不清楚是否需要原地更改源字符串或复制到另一个字符数组。

标签: c c-strings


【解决方案1】:

您不能使用 C 中的++= 运算符连接字符串或字符。您必须定义一个足够大的char 数组以接收新字符串并将适当的字符一次存储到其中。

您可能希望将每个单词的首字母复制到缓冲区而不是空格后面的每个字符。

这是修改后的版本:

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

【讨论】:

    【解决方案2】:

    如果你想将结果连接成一个字符串,'result'应该是一个字符数组:

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

    您的代码的另一个问题是它不会读取第一个单词,因为它之前没有空格。解决此问题的一种方法是将字符串的第一个分配给单词的第一个元素:

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

    你也可以使用'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];
    }
    

    请注意,“结果”数组的大小是任意的,并且仅适用于 3 个或更少的单词。您可以创建一个类似的 for 循环来计算字符串中的空格数以找出有多少单词。

    【讨论】:

    • 神奇的数字 4 和 5 是什么?
    • @VladfromMoscow 4 是包含最终字符串的数组的大小:“sip\0”
    • 你为什么会这样决定?!源字符串可以包含任意数量的单词。你必须提供一个通用的方法。
    • @VladfromMoscow "请注意,'result' 数组的大小是任意的,仅适用于 3 个或更少的单词。您可以创建一个类似的 for 循环来计算字符串中的空格数找出有多少个单词。”
    【解决方案3】:

    如果您需要更改源数组,使其仅包含存储字符串中单词的第一个字符,则程序可以如下所示。

    #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;
            if ( *q ) ++q;
            p += strcspn( p, delim );
        }
    
        puts( s );
        
        return 0;
    }
    

    程序输出是

    啜饮

    【讨论】:

    • 程序输出将包括s中的初始空白,并且循环将在p到达字符串末尾后不必要地迭代多次,而*q++ = *p覆盖初始的其余部分带有空字节的字符串:)
    • @chqrlie 我故意保留前导空格,因为修剪空格不是一项任务。
    • 我不同意:问题是获取一个字符串,检查该字符串中是否有空格,然后从该主字符串中空格后面的字母创建一个新字符串 明确表示新字符串由字母组成。此外,它应该是一个新字符串,覆盖主字符串似乎不合适。最后,您的程序在p 无缘无故到达空终止符后继续循环。
    • @chqrlie 从描述中不清楚究竟需要做什么。而且提供的代码没有意义。
    • 代码尝试连接源字符串中空格后面的字符,方法是将它们添加到result,就像在 Javascript 或 Python 中所做的那样。显然,这在 C 中不起作用,但意图相对明确,尽管 OP 可能不是母语人士,我们也不是。
    猜你喜欢
    • 2012-05-10
    • 2022-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多