c - 标记字符串并将其作为数组返回

标签 c token tokenize c-strings strtok

我正在尝试对传递的字符串进行标记,将标记存储在数组中并返回它。我在 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]
 }
 ^

最佳答案

编译器已经报告该函数

//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

关于c - 标记字符串并将其作为数组返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60218137/

相关文章:

函数返回类型返回结构指针的编译器抛出错误

javascript - Angular 2 : Uncaught SyntaxError: Unexpected token <

bash 解析文件名

python-3.x - 如何将标记化应用于 TensorFlow 数据集?

c++ - 如何使用 Boost Regex 标记化 C++

c - 独特的字符串生成器

c - 如何解释C代码: char *s = "hello " "world";

php - JWT:如何在 header 中发送授权?

c++ - 在 C++ 中匹配 '|'(垂直线)字符

使用 ## 和 __LINE__ 创建 C 宏(与定位宏的标记串联)