【问题标题】:Split line into array of words + C将行拆分为单词数组 + C
【发布时间】:2014-10-12 21:33:50
【问题描述】:

我正在尝试将一行拆分为一组单词,但我被困在如何在 C 中做到这一点。我的 C 技能不是很好,所以我想不出一种方法来“执行“ 我的点子。她是我目前所拥有的:

int beginIndex = 0;
int endIndex = 0;
int maxWords = 10;
while (1) {
   while (!isspace(str)) {
      endIndex++;
   }
   char *tmp = (string from 'str' from beginIndex to endIndex)
   arr[wordCnt] = tmp;
   wordCnt++;
   beginIndex = endIndex;
   if (wordCnt = maxWords) {
       return;
   }
}

在我的方法中,我收到 (char *str, char *arr[10]),str 是我遇到空格时要拆分的行。 arr 是我要存储单词的数组。有什么方法可以将我想要的字符串的“块”从“str”复制到我的 tmp 变量中?这是我现在能想到的最好的方法,也许这是一个糟糕的想法。如果是这样,我很乐意获得一些关于更好方法的文档或提示。

【问题讨论】:

  • 可以使用strtok将字符串拆分成单词
  • 你有什么问题?
  • 谢谢! strtok 进行了第一次尝试 :) 但是,我使用 main 中的一行调用此方法,并且我知道我需要在某处分配内存。在我将它从 main 发送到这个方法之前,我应该为我的 char arr[10] 分配内存吗?

标签: c arrays split


【解决方案1】:

您应该查看 C 库函数 strtok。您只需将要拆分的字符串和一串分隔符提供给它。

这是一个工作原理示例(取自链接网站):

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

int main ()
{
  char str[] ="- This, a sample string.";
  char * pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str," ,.-");

  while (pch != NULL) {
    printf ("%s\n",pch);
    pch = strtok (NULL, " ,.-");
  }

  return 0;
}

在您的情况下,您可以将 strtok 返回的指针分配给数组 arr 中的下一个元素,而不是打印每个字符串。

【讨论】:

    【解决方案2】:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <ctype.h>
    
    int split(char *str, char *arr[10]){
        int beginIndex = 0;
        int endIndex;
        int maxWords = 10;
        int wordCnt = 0;
    
        while(1){
            while(isspace(str[beginIndex])){
                ++beginIndex;
            }
            if(str[beginIndex] == '\0')
                break;
            endIndex = beginIndex;
            while (str[endIndex] && !isspace(str[endIndex])){
                ++endIndex;
            }
            int len = endIndex - beginIndex;
            char *tmp = calloc(len + 1, sizeof(char));
            memcpy(tmp, &str[beginIndex], len);
            arr[wordCnt++] = tmp;
            beginIndex = endIndex;
            if (wordCnt == maxWords)
                break;
        }
        return wordCnt;
    }
    
    int main(void) {
        char *arr[10];
        int i;
        int n = split("1st 2nd 3rd", arr);
    
        for(i = 0; i < n; ++i){
            puts(arr[i]);
            free(arr[i]);
        }
    
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-23
      • 1970-01-01
      • 1970-01-01
      • 2011-05-13
      相关资源
      最近更新 更多