이 프로그램의 목표는 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() 메서드는 string을 분할하여 벡터 클래스의 배열 목록 유형을 반환합니다.
예시
#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