繁体   English   中英

如何在c中按char复制字符串char?

[英]How to copy string char by char in c?

我在堆上声明了一块内存。

char *str;
str = (char *)malloc(sizeof(char) * 10);

我有一个const字符串。

const char *name = "chase";

因为*name短于10所以我需要用chase加5个空格来填充str

我试图循环并设置str[i] = name[i]但是有些东西我没有匹配,因为我无法为其他字符分配空格。 这就是我要去的地方,只是尝试用所有空间填充str来开始

int i;
for (i = 0; i < 10; i++)
{
    strcpy(str[i], ' ');
    printf("char: %c\n", str[i]);
}

正如其他人指出的那样,您需要

 //malloc casting is (arguably) bad
 str = malloc(sizeof(char) * 11);

然后,做

 snprintf(str, 11, "%10s", name);

使用snprintf()而不是sprintf()将防止溢出,并且%10s将根据需要填充结果字符串。

http://www.cplusplus.com/reference/cstdio/snprintf/

如果希望str具有10个字符并且仍然是C字符串,则需要'\\0'终止它。 你可以做到这一点malloc荷兰国际集团str至11的长度:

str = malloc(11);

注意,不需要malloc的返回指针。 另外, sizeof(char)始终为1,因此无需将其乘以所需的char数。

你以后malloc的内存,因为你需要,你可以使用memset设置所有char s到' ' (空格字符)的最后一个元素除外。 最后一个元素必须为'\\0'

memset(str, ' ', 10);
str[10] = '\0';

现在,使用memcpyconst C字符串复制到str

memcpy(str, name, strlen(name));

易于使用的snprintf像这样

#include <stdio.h>
#include <stdlib.h>

int main(){
    char *str;
    str = (char *)malloc(sizeof(char)*10+1);//+1 for '\0'
    const char *name = "chase";

    snprintf(str, 11, "%-*s", 10, name);//11 is out buffer size
    printf(" 1234567890\n");
    printf("<%s>\n", str);
    return 0;
}

暂无
暂无

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

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