【问题标题】:Tokenizing a string and return it as an array标记字符串并将其作为数组返回
【发布时间】:2020-02-13 23:49:02
【问题描述】:

我正在尝试对传递的字符串进行标记,将标记存储在数组中并返回它。我在ubuntu上运行这个。显然,当谈到这种语言时,我被难住了。

示例输入:coinflip 3

我的代码思考过程如下:

take: string
if string = null: return null
else:
while temp != null
   token[i++] = temp
   temp = get next token
return

这是我目前的解决方案。分隔符是空格。 C 已经有一段时间不是我的强项了。

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

//Clears the screen and prompts the user
void msg()
{
    static int init = 1;
    if(init)
    {
        printf("\e[1;1H\e[2J");
        init = 0;
    }
    printf("%s", "uab_sh > ");

}

//Reads in line
char *readIn(void)
{
    char param[101];
    fgets(param, 101, stdin);
    return param;
}

//parse string - still working out the kinks :)
char **parseString(char *cmd)
{
    char delim[] = " ";
    char* temp = strtok(cmd, delim);
    if (temp == " ")
    {
        return NULL;
    }
    else
    {
        int i = 0;
        char** tokens = malloc(3 * sizeof(char*));
        while (temp != NULL)
        {
            tokens[i++] = temp;
            temp = strtok(NULL, " ");
        }
        for (i = 0; i < 3; i++)
        {
            printf("%s\n", tokens[i]);
        }
        return tokens;
    }
}

//Command
int command(char ** cmd)
{
    int pid;
    if (cmd[0] != NULL)
    {
        pid = fork();
        if (pid == 0)
        {
            exit(0);
        }
        else if (pid < 0)
        {
            perror("Something went wrong...");
        }
    }
    else
        return 1;
}


int main()
{
    char *line;
    char **cmd;
    int stat = 0;
    while (1)
    {
        msg();
        line = readLine();
        cmd = parseString(line);
        stat = command(cmd);
        if (stat == 1)
        {
            break;
        }
    }
    return 0;
}

当前错误:

main.c: In function ‘readIn’:
main.c:24:9: warning: function returns address of local variable [-Wreturn-local-addr]
  return param;
         ^~~~~
main.c: In function ‘parseString’:
main.c:32:11: warning: comparison with string literal results in unspecified behavior [-Waddress]
  if (temp == " ")
           ^~
main.c: In function ‘command’:
main.c:59:9: warning: implicit declaration of function ‘fork’ [-Wimplicit-function-declaration]
   pid = fork();
         ^~~~
main.c: In function ‘main’:
main.c:82:10: warning: implicit declaration of function ‘readLine’; did you mean ‘readIn’? [-Wimplicit-function-declaration]
   line = readLine();
          ^~~~~~~~
          readIn
main.c:82:8: warning: assignment makes pointer from integer without a cast [-Wint-conversion]
   line = readLine();
        ^
main.c: In function ‘command’:
main.c:71:1: warning: control reaches end of non-void function [-Wreturn-type]
 }
 ^

【问题讨论】:

  • char* temp 是正确的。 strtok 返回一个指针。此外,您必须将 cmd 作为 char* 传递
  • @JB1 这个条件 cmd == 1 是什么意思?
  • @JB1 也不清楚是否可以更改传递的字符串。
  • 所以我们不需要实际编译和运行您的代码:它有什么问题?
  • @Vlad 我在另一篇文章中读到 strtok() 返回一个 int。既然你指出了,我就删除它。

标签: c token tokenize c-strings strtok


【解决方案1】:

编译器已经报告了这个函数

//Read-in string
char *readIn(void)
{
    char param[101];
    fgets(param, 101, stdin);
    return param;
}

具有未定义的行为,因为它返回指向本地数组 param 的指针,该数组在退出函数后将不再存在。

在这个函数中

char *parseString(char* cmd)
{
    char* temp = strtok(cmd, " ");
    if (cmd == NULL)
    {
        return temp;
    }
    else
    {
        int i = 0;
        char *tokens[3];
        while (temp != NULL)
        {
            tokens[i++] = temp;
            temp = strtok(NULL, " ");
        }
        for (i = 0; i < 3; i++)
        {
            printf("%s\n", tokens[i]);
        }
        return tokens;
    }
}

同样的问题(如果不考虑错误的实现)还有返回表达式的类型

        return tokens;

与函数的返回类型不对应,因为return语句中的表达式类型为char **,而函数的返回类型为char *

我相信对你来说最困难的是编写将字符串拆分为标记的函数。

它可以如下面的演示程序所示。该函数为指向标记的指针数组动态分配内存。如果分配失败,该函数将返回 NULL。否则,函数返回指向动态分配的指针数组的第一个元素的指针。数组的最后一个元素包含 NULL。此元素可用于确定指向数组中标记的实际指针的数量。

你来了。

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

char ** parseString( char *cmd )
{
    char **tokens = malloc( sizeof( char * ) );
    *tokens = NULL;
    size_t n = 1;

    const char *delim = " \t";

    char *p = strtok( cmd, delim );

    int success = p != NULL;

    while ( success )
    {
        char **tmp = realloc( tokens, ( n + 1 ) * sizeof( char * ) );

        if ( tmp == NULL )
        {
            free( tokens );
            tokens = NULL;

            success = 0;
        }
        else
        {
            tokens = tmp;

            tokens[n - 1] = p;
            tokens[n] = NULL;
            ++n;

            p = strtok( NULL, delim );

            success = p != NULL;
        }
    }

    return tokens;
}

int main(void) 
{
    char cmd[] = "Many various and unique commands";

    char **tokens = parseString( cmd );

    if ( tokens != NULL )
    {
        for ( char **p = tokens; *p != NULL; ++p )
        {
            puts( *p );
        }
    }

    free( tokens );

    return 0;
}

程序输出是

Many
various
and
unique
commands

【讨论】:

  • 比我的更完整的解决方案 +1
  • return 语句中的表达式的类型是char **,而函数的返回类型是char * 实际上是char *[3],而不是char **。跨度>
  • @S.S.Anne 函数可能没有数组类型的返回类型。:) return 语句中使用的表达式被隐式转换为指向数组第一个元素的指针,并且类型为 char ** .
  • 对不起。我在想一个指向数组的指针,而不是指针数组。
【解决方案2】:

这里有一个反复的递归解决方案。这个习惯用法使用调用堆栈作为临时空间,以便只分配令牌数组一次。由于它需要很少的簿记,因此代码被彻底简化。不是每个人都会觉得这很有吸引力。

#include <stdlib.h>
#include <string.h>
static char** helper(char* token, int argc) {
  char** retval = token ? parseString(strtok(NULL, " "), argc + 1)
                        : malloc((argc + 1) * sizeof *retval);
  if (retval) retval[argc] = token;
  return retval;
}

char** parseString(char* cmd) {
  return helper(strtok(cmd, " "), 0);
}

当然,递归实现意味着包含大量标记的行可能会溢出堆栈。实际上,我并不担心这一点,因为helper 的堆栈帧非常小,并且没有 VLA、allocas 甚至未初始化的本地变量。因此堆栈溢出将 (1) 需要很多令牌,并且 (2) 可靠地命中保护页面,如果有,则终止进程。如果您使用的是没有堆栈保护的操作系统,则可以在函数中检查递归深度,因为第二个参数跟踪深度。

【讨论】:

    【解决方案3】:

    好吧,除了这段代码不能处理不超过 3 个标记的事实之外,它还有另一个基本问题:它将返回一个非法的内存指针temptokens 是位于 parseString() 函数的堆栈框架内的变量。因此,当它执行完成时,这些变量将消失。这里理想的解决方案是在堆中分配tokens

    这是我的解决方案:

    char** parseString(char* cmd)
    {
        char delimiters[] = " ";
        char* temp = strtok(cmd, delimiters);
        //If temp is NULL then the string contains no tokens
        if (temp == NULL)
        {
            return NULL;
        }
        else
        {
            int i = 0;
            char** tokens = malloc(3*sizeof(char*));
            while (temp != NULL)
            {
                tokens[i++] = temp;
                temp = strtok(NULL, " ");
            }
            for (i = 0; i < 3; i++)
            {
                printf("%s\n", tokens[i]);
            }
            return tokens;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-28
      • 1970-01-01
      • 1970-01-01
      • 2012-10-27
      相关资源
      最近更新 更多