我在 C 中有以下代码:
char *str = "Hello World";
char *s = malloc(strlen(str));
int i =0;
for(;i<strlen(str)-5;i++)
{
s += *(str+i);
}
printf(s);
它什么也没显示。我想要的是获取存储在s
中的str
的子串。
在 Java 中,我会执行以下操作:
String str = "Hello World";
String s="";
for(int i=0;i<str.length()-5; i++)
s+=str[i];
System.out.println(s);
或者改为使用 substring 方法。例如 String s = str.substring(1,2);
。
我怎样才能实现它?
最佳答案
使用strcpy
函数。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[] )
{
char *str = "Hello World";
size_t length = strlen(str);
char *s = (char*)malloc(sizeof(char) * (length + 1));
strcpy(s, str);
s[length] = '\0'; // makes sure it's NUL terminated
printf("%s", s);
free(s);
return 0;
}
分配目标缓冲区时,请注意字符串以NUL
字符结束。
要只复制一个子字符串,使用strncpy
:
strncpy(s, str + 6, strlen(str) - 6);
只会将“World”复制到s
。
在任何情况下,请确保您的 C 字符串在使用 printf
等函数之前以 NUL
终止。
另见 strcat
和 strncat
。还有,熟悉 C 数组和指针。
关于c - 追加字符以获取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1954635/