用星号替换 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

现在,根据算法编写以下代码。在此,string 的 strtok() 方法分割字符串并返回向量类数组列表类型。

示例

#include <cstring>
#include <iostream>
#include <vector>
#include <string.h>
//method for spliting string
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 = "";
   // Creating the censor which is an asterisks
   // "*" text of the length of censor word
   std::string stars = "";
   std::string word = "ajay";
   for (int i = 0; i < word.length(); i++)
      stars += '*';
      // Iterating through our list
      // of extracted words
      int index = 0;
      for (std::string i : word_list){
         if (i.compare(word) == 0)
         // changing the censored word to
         // created asterisks censor
         word_list[index] = stars;
         index++;
      }
      // join the words
      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

更新时间:29-Nov-2019

572 浏览

开启你的 职业

完成课程,获得认证

开始
广告