【问题标题】:store pointer to words in sentence在句子中存储指向单词的指针
【发布时间】:2018-04-11 02:32:07
【问题描述】:

我遇到了一个问题,当将指向句子中字符的指针存储到新数组中时,如果我在句子中添加一个 '\0' 字符来拆分程序提前结束的单词,但是如果我这样做了不添加该字符,那么新数组存储的单词太多。

   int prevSpace = 1;
   for(int i = 0; i < (strlen(sentence)); i++){
       if(sentence[i] != ' ' && prevSpace == 1){
          prevSpace = 0;
          List[j] = &sentence[i];
          printf("list[%d] now points to %c\n", j, sentence[i]);
          j++;
       }

       if(sentence[i] != ' '){
           prevSpace = 0;
       }

       if(sentence[i] == ' '){
           /*if we find space and last char was not a space, add '\0'
           if(prevSpace == 0){
              printf("end added\n");
              sentence[i] = '\0';        /**** <<<FOCUS ON THIS LINE! */
           }

           prevSpace = 1;
       }
   }

   /*finish List with NULL*/
   List[j] = NULL;


   /*print out list of words*/
   for(int i = 0; i < count; i++){
      printf("List[%d] = %s\n", i, List[i]);
   }

这段代码的问题是,数组列表没有每个单词,它只有第一个单词,然后是许多空值。对于“测试一二三”这句话,输出为:

list[0] now points to t

List[0] = test
List[1] = (null)
List[2] = (null)
List[3] = (null)

如果我将重要的行更改为 line[i] = 'X';

那么“测试一二三”句子的输出是:

list[0] now points to t
list[1] now points to o
list[2] now points to t
list[3] now points to t

List[0] = testX  oneX  twoX  three
List[1] = oneX  twoX  three
List[2] = twoX  three
List[3] = three

但这很糟糕,因为我希望 list[0] 只有“test”,list[1] 只有“one”,list[2] 只有“two”,而 list[3] 只有有“三”。我需要一种方法来解决这个问题,以便我可以使用字符串字符 '\0' 的结尾。

【问题讨论】:

    标签: c arrays string pointers


    【解决方案1】:

    您的问题是您试图将所有内容都留在string[] 中,而不是将内容复制到list[] 中。您的for 循环有问题,因为它会重新检查strlen[string],并且在您添加\0 后,您已经缩短了string,因此循环将停止。

    我不知道你是如何处理内存的,但最好有类似的东西

    char word[50][50]  //choose the values to suit - 1st is max words, 
                       //  2nd is max length of word
    
    int i, j, k; 
    //new loop
    for(i = 0, j=0,k=0; i < (strlen(sentence)); i++, k++)
    {
      word[j][k]=string[i];
      if (word[j][k]=' ')
      {
         word[j][k]=0;
         j++; k=0;  // to move to next word 
      }
    }
    

    这段代码应该是您将句子中的单词放入二维数组 word[][]

    所需的全部内容

    【讨论】:

    • 哦,天哪,现在这么有意义。我制作了一个可变“长度”并将其用于循环,并且效果很好。
    • @SJiles 很高兴它起作用了——你可以试试上面的代码,它做的事情有点不同,并将句子中的单词移动到一个新的数组中......但很高兴它对你有用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-18
    • 2012-09-25
    • 2014-12-19
    • 2022-10-01
    • 2014-08-16
    • 1970-01-01
    相关资源
    最近更新 更多