微软面试题之一(版本2.0)

/*设计一数据结构,实现对单词(限于a到z的26个字母)的存储,并可实现查询,如输入"ab",则返回所有以ab开头的单词.

在偶的程序里,我是打开一个文件,然后从文件中读取单词,核心技术还是使用strtok,用strtok分离出单词后,存在自定义的数据结构里面。最终由用户输入前面的几个字母,进行查询输出*/

#include<iostream>
#include<vector>
#include<fstream>

using namespace std;

char seps[]   = " ,/t/"/n.?";
char *token;

typedef class st
{
public:
    int co ; //the couter of words.
    string str; //store the word.
    st():co(0),str(""){ }
}search_word;

int main()
{
    vector<search_word> vec;
    st word;
   
    ifstream ifs("Test.txt");
    if(ifs == NULL)
    {
        cerr<<"The file was not opened."<<endl;
        exit(1);
    } 
    string strTemp;
    string src;
   
    while(getline(ifs,strTemp))
    {
        src += strTemp;
    }
    cout<<src<<endl;
    cout<<"=========================================="<<endl;
   
    int si = src.size();
    char *pstr = new char[si +1];
    strcpy(pstr,src.c_str());
   
    token = strtok(pstr,seps);
    while(token != NULL)
    {
         strTemp = token;
         word.str = strTemp;
         ++word.co;
   
         vec.push_back(word);
         token = strtok(NULL,seps);
    }
   
    vector<search_word>::iterator ite;
    for(ite = vec.begin();ite != vec.end();++ite)
    {
         cout<<(*ite).str<<"   ";
    }
   
   
    cout<<endl<<endl;
    cout<<"The number of the words is : "<<word.co<<endl;
   
    string alphas;
    bool successful = false;
   
    cout<<"You can search words."<<endl;
    cout<<"Please input the front alphas."<<endl;
    cin>> alphas;
    int sa = alphas.size();
    for(ite = vec.begin();ite != vec.end();++ite)
    {
         strTemp = ((*ite).str).substr(0,sa);
         if( strTemp == alphas)
         {
             successful = true;
             cout<<(*ite).str<<"   ";
         }
    }
    cout<<endl<<endl;
    if(!successful)
    {
        cout<<"I am sorry.I can't find some words that you want ."<<endl;
    }
    delete []pstr;
    system("pause");
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值