如何使用 C 字符串进行标记化?

问题描述 投票:0回答:1

如何在 c 字符串中做到这一点?如果我们有一个 c 字符串

char s[20] = "fd50 fd 50 fd 5  0";

我希望我的 2D 字符数组

token
包含这样的分割字符串:

token[0] = "fd"
token[1] = "50"
token[2] = "fd"
token[3] = "50"
token[4] = "fd"
token[5] = "50"

我需要一种方法来拆分数字和字母并将它们单独存储到 2D 字符数组中。

我知道如何用空格进行标记,但是如何像上面那样进行标记呢? 真的不明白如何用 c strings 做到这一点。

到目前为止,我在 C++ 中想到的是:

stringInputChecker(s);
 
std::vector <std::string> token;
std::stringstream check(s);
std::string buffer;
int checker = 1;

while(getline(check, buffer, ' ')) 
{ token.push_back(buffer); }

这里我使用了

std::getline()
函数,以空格作为分隔符。这就是我一直在我的项目中使用的。

但是现在我必须让它在字母和数字之间没有空格的情况下工作

但是这使用了我不想使用的

std::vector
。我对如何在 c 中执行此操作感到困惑。

上面的代码只有在有空格的情况下才有效。如果没有空间就无法工作。

c++ c-strings
1个回答
0
投票

这里下雨天,所以这是你的解决方案......

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

int main( void ) {
    char *str = "fd 50 rt 50 lt50 circle50"; // one sample string
    char **tok = NULL;
    char holding[ 32 ] = { 0 }; // a temp buffer to accumulate characters
    size_t n = 0, nt = 0;

    for( char *cp = str; *cp; cp++ ) {
        if( *cp == ' ' ) // ignore whitespace
            continue;

        if( !holding[0] ) { // first non-whitespace character
            holding[ n++ ] = *cp;
            continue;
        }

        if( isalpha( holding[0] ) && isalpha( *cp ) ) { // accumulate alpha chars
            holding[ n++ ] = *cp;
            continue;
        }

        if( isdigit( holding[0] ) && isdigit( *cp ) ) { // accumulate digits
            holding[ n++ ] = *cp;
            continue;
        }

        holding[ n ] = '\0'; // terminate buffer

        tok = realloc( tok, (nt+1) * sizeof *tok ); // extend array of ptrs
        tok[ nt++ ] = strdup( holding ); // copy the string

        n = 0; // reset
        holding[ n++ ] = *cp; // store whatever is here
    }

    if( n ) { // handle what remains in buffer
        holding[ n ] = '\0';
        tok = realloc( tok, (nt+1) * sizeof *tok );
        tok[ nt++ ] = strdup( holding );
    }

    // proof
    for( size_t i = 0; i < nt; i++ )
        printf( "tok[%u] = \"%s\"\n", i, tok[i] );

    return 0;
}

结果:

tok[0] = "fd"
tok[1] = "50"
tok[2] = "rt"
tok[3] = "50"
tok[4] = "lt"
tok[5] = "50"
tok[6] = "circle"
tok[7] = "50"

这可能会“简化”一点,但为什么要麻烦呢?像这样展开,很容易看到发生了什么以及发生在哪里。

© www.soinside.com 2019 - 2024. All rights reserved.