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>
//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
-
C++でのコンマ区切りのstd::stringの解析
このプログラムでは、C++でコンマ区切りの文字列を解析する方法を説明します。いくつかのテキストが存在し、それらがコンマで区切られている場所に文字列を配置します。このプログラムを実行すると、それらの文字列がベクトル型オブジェクトに分割されます。 それらを分割するには、getline()関数を使用しています。この関数の基本的な構文は次のとおりです。 getline (input_stream, string, delim) この関数は、入力ストリームから文字列または行を読み取るために使用されます。 Input: Some strings "ABC,XYZ,Hello,World,25
-
C ++で単一の文字を文字列に変換するにはどうすればよいですか?
単一の文字を文字列に変換する方法はいくつかあります。次の例では、それらの一部を使用して文字を文字列に変換しています。 これは、C++言語で単一の文字を文字列に変換する例です。 例 #include <iostream> #include<string> #include<sstream> int main() { char c = 'm'; std::string s(1, c); std::cout << "Using string c