Computer >> Máy Tính >  >> Lập trình >> C ++

Thay thế các từ bằng dấu hoa thị trong C ++

Mục đích của chương trình này là thay thế một từ cụ thể bằng dấu hoa thị trong chuỗi bằng cách sử dụng mã lập trình c ++. Chức năng thiết yếu của bài luận lớp vectơ và chuỗi đóng một vai trò quan trọng để đạt được kết quả tương lai. Thuật toán như sau;

Thuật toán

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

Bây giờ, đoạn mã sau được tạo ra dựa trên thuật toán. Ở đây, phương thức strtok () của chuỗi sẽ chia chuỗi và trả về kiểu danh sách mảng của lớp vectơ.

Ví dụ

#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;
   }
}

Như đã thấy trong đoạn mã trên, tất cả mã hoạt động của chuỗi được gói vào phương thức getChar (), sau này, lệnh gọi này sẽ được chuyển đến việc thực thi chương trình main ().

Đầu ra

String before replace::Hello ajay yadav ! you ajay you are star
Word to be replaced::ajay
Output::Hello **** yadav ! you **** you are star