我的字符串末尾有一些空格。我想在第一个空格出现时在该位置终止此字符串,以便以后strncpy()
使用它时,它将仅复制字符串中不包含空格的部分。
这是一些尝试,显然给了我一个segault。我该怎么办我打算做的事?
int main() {
char* s1 = "SomeString ";
*(s1 + 10)='\0';
printf("%s\n",s1);
return 0;
}
您正试图修改一个只读字符串,这是因为声明它的方式指向一个恒定值。您必须先制作一个副本:
#include <stdio.h>
#include <string.h>
int main() {
char* s1 = "SomeString ";
char *s2 = strdup(s1);
char *s3 = strchr(s2, ' ');
*s3 = '\0';
printf("%s\n",s2);
/* if not needed any more, because strdup allocates heap memory */
free(s2);
return 0;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句