【问题标题】:add char to string without help of functions在没有函数帮助的情况下将字符添加到字符串
【发布时间】:2013-03-02 06:34:56
【问题描述】:

对于我的程序,我需要在不使用标准库或 IO 函数的情况下将 char(char) 添加到 string(char *)。 例如:

char *s = "This is GOO";
char c = 'D';

s = append(s, c);

和 s 会产生字符串“This is GOOD”。 是否有一些适当的方法来操作数组以实现这一目标? 同样,从字符数中生成字符串就足够了。 我很确定我可以使用 malloc,但不是积极的......

char * app(char* s, char c){
    char *copy;
    int l = strlen_(s);
    copy = malloc(l+1);
    copy = s;
    copy[l] = c;
    copy[l+1] = '\0';
    return copy;
}

不能使用 strcpy

【问题讨论】:

    标签: c arrays string char append


    【解决方案1】:

    在不泄露答案的情况下,因为这听起来像是课堂作业,所以这是您想要在高层次上做的事情:

    1. 确定字符串的长度,即找到'\0' 终止符。
    2. 分配一个长一个字符的新 char 数组。
    3. 将旧字符串复制到新字符串中。
    4. 在末尾添加新字符。
    5. 确保在新字符串的末尾有一个 '\0' 终止符。

    (如果您被允许修改现有字符串,那么您可能会跳过步骤 2 和 3。但在您的示例中,char *s = "This is GOO"s 指向不可修改的字符串文字,这意味着您不能在放置并且必须使用副本。)


    对您发布的代码的评论:

    char * app(char* s, char c) {
        char *copy;
        int l = strlen_(s);
        copy = malloc(l+1);    /* should be +2: +1 for the extra character and +1 for \0 */
        copy = s;              /* arrays must be copied item by item. need a for loop */
        copy[l] = c;
        copy[l+1] = '\0';
        return copy;
    }
    

    【讨论】:

    • s = append(s, c); 暗示s 不会被append 修改,除非append 有一个真正可怜的规范。
    • ' char * app(char* s, char c){ char *copy; int l = strlen_(s);复制 = malloc(l+1);复制 = s;复制[l] = c;复制[l+1] = '\0';返回副本; } ' 分段错误 =/
    • 如何使这种格式像这里的代码一样...?无论如何,如何在没有 strcpy 的情况下将旧字符串复制到新字符串
    • @duskast 给了我答案,你给了我理解,非常感谢
    【解决方案2】:
    #include <stdlib.h>
    
    char *append(char *s, char c)
    {
        int i = 0, j = 0;
        char *tmp;
        while (s[i] != '\0')
            i++;
        tmp = malloc((i+2) * sizeof(char));
        while (j < i)
        {
            tmp[j] = s[j];
            j++;
        }
        tmp[j++] = c;
        tmp[j] = '\0';
        return tmp;
    }
    
    int main(void)
    {
        char *s = "This is Goo";
        char c = 'D';
        s = append(s, c);
        return 0;
    }
    

    【讨论】:

    • a) 使用 strlen b) sizeof(char) 始终为 1 c) 使用 memcpystrcpy
    • 糟糕,抱歉,错过了不能使用strcpy 的要求。不过,关于strlenmemcpy 什么也没说。
    猜你喜欢
    • 2013-05-05
    • 2015-09-06
    • 2011-05-13
    • 1970-01-01
    • 2012-01-26
    • 2015-07-26
    • 2017-04-01
    • 1970-01-01
    • 2023-03-18
    相关资源
    最近更新 更多