【问题标题】:Is there a C method to split a one-line input?是否有 C 方法来拆分单行输入?
【发布时间】:2021-12-05 23:57:14
【问题描述】:

我想知道如何在不使用 库的情况下拆分单行输入并使用 malloc() 为输入的每个“元素”分配内存空间。

【问题讨论】:

  • 如果你不想使用字符串库,你将不得不编写自己的函数/库
  • 相关函数在 string.h 中,所以如果你不使用 string.h,请自己编写。这很简单 - 只需迭代字符串并查找分隔符。没什么特别的。但是,我们不会编写您的代码。
  • 如果你转储作业,你也应该转储问题的任何约束。这可以防止其他用户在您的教授明确排除的答案上浪费时间。

标签: c input split malloc realloc


【解决方案1】:

请您尝试以下方法:

#include <stdio.h>
#include <stdlib.h>
#define MAXTOK 100      // maximum number of available tokens

int
main()
{
    char str[] = "Hello! We are learning about string manipulation";

    int i, j;
    int len;            // length of each token
    char delim = ' ';   // delimiter of the tokens
    char *tok[MAXTOK];  // array for the tokens
    int n = 0;          // number of tokens

    i = 0;              // position in str[]
    while (1) {
        // increment the position until the end of string or the delimiter
        for (len = 0; str[i] != '\0' && str[i] != delim; len++) {
            i++;
        }
        // check the count of tokens
        if (n >= MAXTOK) {
            fprintf(stderr, "token count exceeds the array size\n");
            exit(1);
        }
        // allocate a buffer for the new token
        if (NULL == (tok[n] = malloc(len + 1))) {
            fprintf(stderr, "malloc failed\n");
            exit(1);
        }
        // copy the substring
        for (j = 0; j < len; j++) {
            tok[n][j] = str[i - len + j];
        }
        tok[n][j + 1] = '\0';           // terminate with the null character
        n++;                            // increment the token counter
        if (str[i] == '\0') break;      // end of str[]
        i++;                            // skip the delimiter
    }

    // print the tokens
    for (j = 0; j < n; j++) {
        printf("%s\n", tok[j]);
    }
}

【讨论】:

    【解决方案2】:

    好吧,能够拆分输入的方法如下,或者至少考虑到您希望为每个“令牌”分配内存空间是最成功的

    #include<stdio.h>
    #include <string.h>
    
    int main() {
       char string[50] = "Hello! We are learning about strtok";
       // Extract the first token
       char * token = strtok(string, " ");
       // loop through the string to extract all other tokens
       while( token != NULL ) {
          printf( " %s\n", token ); //printing each token
          token = strtok(NULL, " ");
       }
       return 0;
    }
    

    并且输出是这样的:

     Hello!
     We
     are
     learning
     about
     strtok
    

    【讨论】:

    • 不使用字符串库和strtok有什么办法吗?
    猜你喜欢
    • 2013-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-05
    • 2023-03-30
    • 2018-07-12
    • 2019-10-05
    • 2020-11-11
    相关资源
    最近更新 更多