将字符串除以几个选项之一

Divided a string by one of a few options

我有一个 char 数组,我想在其中循环,其中除以所有数学运算,

例如,现在我只寻找 = 标志,所以

   for (char *p = strtok(data,"="); p != NULL; p = strtok(NULL, " "))
    {
        numberOfChars++;
    }

我想循环,其中不仅 "=" 是令牌,而且它也可能是其中之一:+,-,*,\,=

这样我们就可以在循环中为其中的每一个递增 numberOfChars

所以对于 : a = b + c 我们将得到 3 .

您可以提供 一组定界符标记 作为 delim

来自 C11 标准,章节 §7.24.5.8

char *strtok(char * restrict s1, const char * restrict s2);

A sequence of calls to the strtok function breaks the string pointed to by s1 into a sequence of tokens, each of which is delimited by a character from the string pointed to by s2. [....]

所以,在你的情况下,如果你想使用 any 来自 =+-*/ 的标记来标记输入字符串,你应该使用类似

char * delim = "=+-*/`";
.
.
char *p = strtok(data, delim);

注意: 正如 BLUEPIXY 在评论中提到的,请注意,

Be cautious when using these functions. If you do use them, note that: These functions modify their first argument. These functions cannot be used on constant strings.The identity of the delimiting byte is lost.


在另一种替代方法中,如果您要计算数学语句中运算符的数量,只需遍历数组并使用 isdigit()/isspace() t0 找出非-数字条目并更新计数器。

你可以简单地遍历字符串

for (size_t i=0; i < strlen(data); i++)
    {
        if ((data[i] == '+') || 
            (data[i] == '-') || 
            (data[i] == '*') || 
            (data[i] == '\') || 
            (data[i] == '='))
        {
            numberOfChars++;
        }
    }