📜  在C++中实现strtok()函数

📅  最后修改于: 2021-05-30 17:55:54             🧑  作者: Mango

strtok()函数用于基于定界符标记字符串。它存在于头文件“ 字符串.h”中,并返回指向下一个令牌的指针(如果存在),如果不存在下一个令牌,则返回NULL。为了获得所有令牌,其想法是循环调用此函数。

头文件:

#include 

句法:

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

在本文中,我们将讨论此函数的实现,其中必须考虑两点:

  • 维护字符串的状态,以确保我们已经提取了多少个令牌。
  • 其次,将提取的令牌列表保留在数组中以将其返回。

脚步:

  • 创建一个函数strtok() ,它接受字符串和定界符作为参数并返回char指针。
  • 创建一个静态变量输入以维护字符串的状态。
  • 检查是否是第一次提取令牌,然后使用它初始化输入
  • 如果输入为NULL并且提取了所有标记,则返回NULL。
  • 在此步骤中,开始提取令牌并将其存储在数组result []中
  • 现在,迭代一个循环直到出现NULL或定界符,然后通过包含‘\ 0’返回结果。
  • 当到达字符串的末尾时(如果需要),则手动添加‘\ 0 ‘并在末尾包括该小写字母。

下面是相同的实现:

C++
// C++ program to demonstrate the function
// strtok() to tokenized the string
#include 
using namespace std;
char* mystrtok(char* s, char d)
{
    // Stores the state of string
    static char* input = NULL;
  
    // Initialize the input string
    if (s != NULL)
        input = s;
  
    // Case for final token
    if (input == NULL)
        return NULL;
  
    // Stores the extracted string
    char* result = new char[strlen(input) + 1];
    int i = 0;
  
    // Start extracting string and
    // store it in array
    for (; input[i] != '\0'; i++) {
  
        // If delimeter is not reached
        // then add the current character
        // to result[i]
        if (input[i] != d)
            result[i] = input[i];
  
        // Else store the string formed
        else {
            result[i] = '\0';
            input = input + i + 1;
            return result;
        }
    }
  
    // Case when loop ends
    result[i] = '\0';
    input = NULL;
  
    // Return the resultant pointer
    // to the string
    return result;
}
  
// Driver Code
int main()
{
    // Given string str
    char str[90] = "It, is my, day";
  
    // Tokenized the first string
    char* ptr = mystrtok(str, ' ');
  
    // Print current tokenized string
    cout << ptr << endl;
  
    // While ptr is not NULL
    while (ptr != NULL) {
        // Tokenize the string
        ptr = mystrtok(NULL, ' ');
  
        // Print the string
        cout << ptr << endl;
    }
    return 0;
}


输出:
It,
is
my,
day
想要从精选的最佳视频中学习和练习问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”