字符串处理转换(华为2013校园招聘上机笔试题 )

来源:互联网 发布:怎样利用网络挣钱 编辑:程序博客网 时间:2024/04/30 23:26

问题描述:    
在给定字符串中找出单词( “单词”由大写字母和小写字母字符构成,其他非字母字符视为单词的间隔,如空格、问号、数字等等;另外单个字母不算单词);找到单词后,按照长度进行降序排序,(排序时如果长度相同,则按出现的顺序进行排列),然后输出到一个新的字符串中;如果某个单词重复出现多次,则只输出一次;如果整个输入的字符串中没有找到单词,请输出空串。输出的单词之间使用一个“空格”隔开,最后一个单词后不加空格。
要求实现函数:
void my_word(charinput[], char output[])
【输入】  char input[], 输入的字符串
【输出】  char output[],输出的字符串
【返回】 无
示例
输入:charinput[]="some local buses, some1234123drivers" ,
输出:charoutput[]="drivers local buses some"
输入:charinput[]="%A^123 t 3453i*()" ,
输出:charoutput[]=""
以上摘自 http://blog.csdn.net/lanyan822/article/details/7983832 ,但是考虑到没有给出这个的源代码,自己随手写了一个,写得不好,仅供娱乐,欢迎大神指点。

#include <string>#include <iostream>#include <algorithm>#include <vector>using namespace std;int my_cmp(string &str1,string &str2)//比较函数{return str1.length() > str2.length();}void my_word(char input[],char output[]){//考虑到存C代码编程复杂,用C++实现算法vector<string> wordList;//单词链表bool flag = true;//表示开始记录单词string temp;//临时单词缓存for(unsigned int i = 0;i < strlen(input);++i)//遍历输入 字符串,必要{if(input[i] == ' ' && !temp.length())//接收到空格表示开始记录切单词缓存为空{flag = true;continue;}if(flag){if((input[i] >= 'a')&&(input[i] <= 'z') ||(input[i] >= 'A')&&(input[i] <= 'Z')){//如果接收到字母开始记录temp += input[i];}else if(input[i] == ' ')//一个单词接受完成{if(temp.length() > 1 && find(wordList.begin(),wordList.end(),temp) == wordList.end())//单个字母不接受且保证不重复插入{wordList.push_back(temp);}temp.clear();}else//接收到其他字符丢弃{flag = false;temp.clear();}}}sort(wordList.begin(),wordList.end(),my_cmp);//字符串长度降序排列int placeFlag = 0;//记录输出字符串当前位置for(unsigned int i = 0;i < wordList.size();++i)//必要转换{strcpy(&output[placeFlag],((string)wordList.at(i)).c_str());//memcpy(&output[placeFlag],((string)wordList.at(i)).c_str(),((string)wordList.at(i)).size());//这种方式对于大数据的情况下效率高很多,但是注意要在output字符串最后加上‘\0’结束符placeFlag += ((string)wordList.at(i)).length();if(i != wordList.size() - 1)//为了满足最后一个单词不加空格output[placeFlag++] = ' ';}}int _tmain(int argc, _TCHAR* argv[]){char getLin[1000];my_word("abc ad a wer fdsaf7897 dfakdjfadfa*%$%^",getLin);return 0;}


 

原创粉丝点击