通过插入空字符在C中拆分字符串

时间:2018-01-29 03:55:00

标签: c split segmentation-fault

我试图通过插入空字符在C中拆分字符串,并且我不断收到错误segmentation fault (core dumped).p[0] = '\0';一直造成这个问题。如何通过在"say hello?

上的空格处插入Null字符来避免这种情况并拆分字符串
char *sentence = "say hello";
printf("You typed: %s\n", sentence);

char *allbutfirst = sentence + 1;
printf("Everythign but first letter is %s\n", allbutfirst);

char *secondpart = sentence + 5;
printf("Skipping the first 5 letters, the rest is %s\n", secondpart);

// strchr finds the first occurence of a letter
char *p = strchr(sentence, ' ');
printf("Everythign starting at first space is %s\n", p);

// turn the space into a '\0' "null character", effectively splitting
// the string into two parts.
p[0] = '\0'; // assign using array notation
// now, sentence ends where the space used to be
// and (p+1) points to the rest of the text.
printf("First word is %s\n", sentence);
printf("Rest of sentence is %s\n", p + 1);

1 个答案:

答案 0 :(得分:1)

这是因为

char *sentence = "say hello";

应该实际声明为

const char *sentence = "say hello";

字符串文字,即用"say hello"等引号编写的代码中的字符串文字 不可变,意味着它们是只读的,你不能改变它们的内容。

char *p = strchr(sentence, ' ');

如果找到空白区域,p仍然指向只读内存,因此

p[0] = '\0';

以段错结束。如果空白区域,strchr也可以返回NULL 找到,当pNULL时,这也会导致段错误。

如何解决?使用char数组,并使用字符串初始化它, 还要检查strchr的返回值:

#include <stdio.h>
#include <string.h>

int main(void)
{
    char sentence[] = "say hello";
    printf("You typed: %s\n", sentence);

    char *allbutfirst = sentence + 1;
    printf("Everythign but first letter is %s\n", allbutfirst);

    char *secondpart = sentence + 5;
    printf("Skipping the first 5 letters, the rest is %s\n", secondpart);

    // strchr finds the first occurence of a letter
    char *p = strchr(sentence, ' ');
    if(p == NULL)
    {
        fprintf(stderr, "Empty space not found\n");
        return 1;
    }
    printf("Everythign starting at first space is %s\n", p);

    // turn the space into a '\0' "null character", effectively splitting
    // the string into two parts.
    p[0] = '\0'; // assign using array notation
    // now, sentence ends where the space used to be
    // and (p+1) points to the rest of the text.
    printf("First word is %s\n", sentence);
    printf("Rest of sentence is %s\n", p + 1);

    return 0;
}