简体   繁体   English

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

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

I have a chunk of memory I'm declaring on the heap. 我在堆上声明了一块内存。

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

I have a const string. 我有一个const字符串。

const char *name = "chase";

Because *name is shorter than 10 I need to fill str with chase plus 5 spaces. 因为*name短于10所以我需要用chase加5个空格来填充str

I've tried to loop and set str[i] = name[i] but there's something I'm not matching up because I cannot assign spaces to the additional chars. 我试图循环并设置str[i] = name[i]但是有些东西我没有匹配,因为我无法为其他字符分配空格。 This was where I was going, just trying to fill str with all spaces to get started 这就是我要去的地方,只是尝试用所有空间填充str来开始

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

As the others pointed out, you need 正如其他人指出的那样,您需要

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

and then, just do 然后,做

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

Using snprintf() instead of sprintf() will prevent overflow, and %10s will pad your resulting string as you want. 使用snprintf()而不是sprintf()将防止溢出,并且%10s将根据需要填充结果字符串。

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

If you want str to have 10 characters and still be a C-string, you need to '\\0' terminate it. 如果希望str具有10个字符并且仍然是C字符串,则需要'\\0'终止它。 You can do this by malloc ing str to a length of 11: 你可以做到这一点malloc荷兰国际集团str至11的长度:

str = malloc(11);

Note there's no need to cast the return pointer of malloc . 注意,不需要malloc的返回指针。 Also, sizeof(char) is always 1 so there's no need to multiply that by the number of char s that you want. 另外, sizeof(char)始终为1,因此无需将其乘以所需的char数。

After you've malloc as much memory as you need you can use memset to set all the char s to ' ' (the space character) except the last element. 你以后malloc的内存,因为你需要,你可以使用memset设置所有char s到' ' (空格字符)的最后一个元素除外。 The last element needs to be '\\0' : 最后一个元素必须为'\\0'

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

Now, use memcpy to copy your const C-string to str : 现在,使用memcpyconst C字符串复制到str

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

easy to use snprintf like this 易于使用的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