在C ++中用星号替换单词
该程序的目的是通过使用c++编程代码用字符串中的星号替换特定的单词。向量和字符串类作文的基本功能对达到预期效果起关键作用。算法如下:
算法
START Step-1: Input string Step-2 Split the string into words and store in array list Step-3: Iterate the loop till the length and put the asterisk into a variable Step-4: Traverse the array foreah loop and compare the string with the replaced word Step-5: Print END
现在,基于该算法,下面的代码被提取出来。在这里,strtok()
字符串方法将字符串拆分,并返回向量类的数组列表类型。
示例
#include <cstring> #include <iostream> #include <vector> #include <string.h> //分割字符串的方法 std::vector<std::string> split(std::string str,std::string sep){ char* cstr=const_cast<char*>(str.c_str()); char* current; std::vector<std::string> arr; current=strtok(cstr,sep.c_str()); while(current!=NULL){ arr.push_back(current); current=strtok(NULL,sep.c_str()); } return arr; } int main(){ std::vector<std::string> word_list; std::cout<<"string before replace::"<<"Hello ajay yadav ! you ajay you are star"<<std::endl; std::cout<<"word to be replaced::"<<"ajay"<<std::endl; word_list=split("Hello ajay yadav ! you ajay you are star"," "); std::string result = ""; //创建一个星号的检查器 // "*" text of the length of censor word std::string stars = ""; std::string word = "ajay"; for (int i = 0; i < word.length(); i++) stars += '*'; //遍历我们的列表 //提取的单词 int index = 0; for (std::string i : word_list){ if (i.compare(word) == 0) //将审查的单词更改为 //创建星号检查器 word_list[index] = stars; index++; } //加入单词 for (std::string i : word_list){ result += i + ' '; } std::cout<<"output::"<<result; return 0; } }
从上面的代码中可以看出,所有字符串操作代码都被捆绑到retrieveChar()方法中,随后该调用被传递给程序main()
执行。
输出结果
String before replace::Hello ajay yadav ! you ajay you are star Word to be replaced::ajay Output::Hello **** yadav ! you **** you are star