You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++如何提取存储句子中的单词以实现后续单词匹配功能

C++ 提取并存储句子中所有单词的实现方案

核心思路

  • 原有逻辑已经实现了单词边界的判断,只需要在每次识别到单词的时候,记录单词的起止位置,截取内容存入可遍历的容器即可
  • 推荐使用std::vector<std::string>存储单词,不需要手动管理内存,后续匹配校验时直接遍历容器即可

完整实现代码

#include <iostream>
#include <cstring>
#include <vector>
#include <string>

// 函数返回存储所有单词的vector,也可以用传引用的方式当参数传入
std::vector<std::string> wordsInString(const char* s)
{
    std::vector<std::string> words;
    int len = strlen(s);
    int i = 0;
    while(i < len)
    {
        // 跳过空白字符
        while(i < len && (s[i] == ' ' || s[i] == '\t' || s[i] == '\n'))
        {
            i++;
        }
        if(i < len)
        {
            int start = i; // 记录单词起始位置
            // 遍历到单词结束位置
            while(i < len && (s[i] != ' ' && s[i] != '\t' && s[i] != '\n'))
            {
                i++;
            }
            // 截取单词存入容器
            words.emplace_back(s + start, i - start);
        }
    }
    std::cout << "The total count: " << words.size() << std::endl;
    return words;
}

int main()
{
    std::vector<std::string> sentenceWords = wordsInString("My name is Donnie");
    
    // 示例:输出所有存储的单词
    std::cout << "提取到的单词如下:" << std::endl;
    for(const auto& word : sentenceWords)
    {
        std::cout << word << std::endl;
    }

    // 示例:匹配校验单词是否存在
    std::string target = "Donnie";
    bool isExist = false;
    for(const auto& word : sentenceWords)
    {
        if(word == target)
        {
            isExist = true;
            break;
        }
    }
    if(isExist)
    {
        std::cout << "单词\"" << target << "\"存在于句子中" << std::endl;
    }
    else
    {
        std::cout << "单词\"" << target << "\"不存在于句子中" << std::endl;
    }
    
    return 0;
}

C风格实现(如需兼容C环境)

如果不想用C++标准库容器,可以用动态分配的char**数组存储单词,注意使用完后需要手动释放每个单词和数组本身的内存,避免内存泄漏:

#include <iostream>
#include <cstring>
#include <cstdlib>

char** wordsInString(const char* s, int* outCount)
{
    int count = 0;
    int len = strlen(s);
    int i = 0;
    // 先统计单词数分配数组空间
    while(i < len)
    {
        while(i < len && (s[i] == ' ' || s[i] == '\t' || s[i] == '\n')) i++;
        if(i < len)
        {
            count++;
            while(i < len && (s[i] != ' ' && s[i] != '\t' && s[i] != '\n')) i++;
        }
    }
    char** words = (char**)malloc(sizeof(char*) * count);
    *outCount = count;
    i = 0;
    int idx = 0;
    while(i < len)
    {
        while(i < len && (s[i] == ' ' || s[i] == '\t' || s[i] == '\n')) i++;
        if(i < len)
        {
            int start = i;
            while(i < len && (s[i] != ' ' && s[i] != '\t' && s[i] != '\n')) i++;
            int wordLen = i - start;
            words[idx] = (char*)malloc(wordLen + 1);
            strncpy(words[idx], s + start, wordLen);
            words[idx][wordLen] = '\0';
            idx++;
        }
    }
    return words;
}

int main()
{
    int count = 0;
    char** words = wordsInString("My name is Donnie", &count);
    std::cout << "单词总数:" << count << std::endl;
    for(int i=0;i<count;i++)
    {
        std::cout << words[i] << std::endl;
        free(words[i]); // 释放每个单词的内存
    }
    free(words); // 释放数组本身的内存
    return 0;
}

内容的提问来源于stack exchange,提问作者Sunny

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 16:15:00