C中的空终止字符串
Null-terminating a string in C
我有一个字符串,末尾有一些 space。我想在第一个 space 出现的位置终止这个字符串,这样当我稍后对它做 strncpy()
时,它只会复制不包含 spaces.
这是一次尝试,显然给了我一个 segault。我怎样才能做我想做的事?
int main() {
char* s1 = "SomeString ";
*(s1 + 10)='[=10=]';
printf("%s\n",s1);
return 0;
}
也许 strstr 对您有用 (http://www.cplusplus.com/reference/cstring/strstr/)
char * pFirstSpace = strstr (s1," ");
if (pFirstSpace) *pFirstSpace=0;
更新
正如许多其他人注意到的那样,这导致了访问冲突。这仅在动态分配的字符上运行。因此,您需要在更改其内容之前将字符串复制到动态缓冲区中
像在 *(s1 + 10)='[=10=]';
中那样修改文字字符串的内容是未定义的行为。
您试图修改一个只读的字符串,因为您声明它指向常量值的方式。您必须先复印一份:
#include <stdio.h>
#include <string.h>
int main() {
char* s1 = "SomeString ";
char *s2 = strdup(s1);
char *s3 = strchr(s2, ' ');
*s3 = '[=10=]';
printf("%s\n",s2);
/* if not needed any more, because strdup allocates heap memory */
free(s2);
return 0;
}
你可以直接使用
char s1[] = "SomeString ";
而不是
char* s1 = "SomeString ";
一个更一般化的示例,您可以在其中实际找到第一个 space 字符(如果有)。还要注意 s1
定义方式的变化,以避免文字字符串(即 "this"
)可能存储在只读内存中的问题。在您的示例中 s1
直接指向文字字符串。下面的文字串用于初始化数组s1.
int main() {
char s1[] = "SomeString ";
char * spc = strchr(s1, ' ');
if (spc != NULL) *spc = '[=10=]';
printf("%s\n",s1);
return 0;
}
我有一个字符串,末尾有一些 space。我想在第一个 space 出现的位置终止这个字符串,这样当我稍后对它做 strncpy()
时,它只会复制不包含 spaces.
这是一次尝试,显然给了我一个 segault。我怎样才能做我想做的事?
int main() {
char* s1 = "SomeString ";
*(s1 + 10)='[=10=]';
printf("%s\n",s1);
return 0;
}
也许 strstr 对您有用 (http://www.cplusplus.com/reference/cstring/strstr/)
char * pFirstSpace = strstr (s1," ");
if (pFirstSpace) *pFirstSpace=0;
更新
正如许多其他人注意到的那样,这导致了访问冲突。这仅在动态分配的字符上运行。因此,您需要在更改其内容之前将字符串复制到动态缓冲区中
像在 *(s1 + 10)='[=10=]';
中那样修改文字字符串的内容是未定义的行为。
您试图修改一个只读的字符串,因为您声明它指向常量值的方式。您必须先复印一份:
#include <stdio.h>
#include <string.h>
int main() {
char* s1 = "SomeString ";
char *s2 = strdup(s1);
char *s3 = strchr(s2, ' ');
*s3 = '[=10=]';
printf("%s\n",s2);
/* if not needed any more, because strdup allocates heap memory */
free(s2);
return 0;
}
你可以直接使用
char s1[] = "SomeString ";
而不是
char* s1 = "SomeString ";
一个更一般化的示例,您可以在其中实际找到第一个 space 字符(如果有)。还要注意 s1
定义方式的变化,以避免文字字符串(即 "this"
)可能存储在只读内存中的问题。在您的示例中 s1
直接指向文字字符串。下面的文字串用于初始化数组s1.
int main() {
char s1[] = "SomeString ";
char * spc = strchr(s1, ' ');
if (spc != NULL) *spc = '[=10=]';
printf("%s\n",s1);
return 0;
}