文字列のすべての異なる文字をC++で順番に出力します
この問題では、文字列が与えられます。私たちのタスクは、文字列のすべての異なる文字を、文字列に表示される順序で印刷することです。
私たちの問題を理解するために例を見てみましょう
Input: tutorials Point Output: uralsPn
この問題を解決する方法は複数ありますが、最も効果的な方法について説明します。単純なものには、ループのネストが含まれます。
このために、サイズ256の2つの配列を使用します(8ビット文字が格納されます)。
まず、カウンター配列のすべての値を0に初期化し、インデックス配列のすべての値をn(文字列の長さ)に初期化します。文字列strの走査時、およびすべての文字cについて、count [x]を増やします(count [x] =1の場合、index [x] =i)。 count [x] =2の場合、index [x]=nです。インデックスを並べ替えて文字を印刷します。
例
ソリューションの実装を示すコード
#include <bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 256;
void printDistinctCharacters(string str) {
int n = str.length();
int count[MAX_CHAR];
int index[MAX_CHAR];
for (int i = 0; i < MAX_CHAR; i++) {
count[i] = 0;
index[i] = n;
}
for (int i = 0; i < n; i++) {
char x=str[i];
++count[x];
if (count[x] == 1 && x !=' ')
index[x] = i;
if (count[x] == 2)
index[x] = n;
}
sort(index, index+MAX_CHAR);
for (int i=0; i<MAX_CHAR && index[i] != n; i++)
cout<<str[index[i]]<<" ";
}
int main() {
string str = "tutorialsPoint";
cout<<"All distinct Characters of the string '"<<str<<"' are :\n";
printDistinctCharacters(str);
return 0;
} All distinct Characters of the string 'tutorialsPoint' are − u r a l s P nです。
-
特定の文字列のすべてのサブ文字列をC++で出力するプログラム
このチュートリアルでは、特定の文字列のすべての部分文字列を出力するプログラムについて説明します。 このために、文字列または文字の配列が提供されます。私たちのタスクは、その特定の文字列のすべてのサブ文字列を出力することです。 例 #include<bits/stdc++.h> using namespace std; //printing all the substrings void print_substr(char str[], int n){ for (int len = 1; len <= n; len++){
-
C++で文字列内のすべての文字を切り替えます
このプログラムは、文字列の文字を大文字に変換します。ただし、このタスクは、c ++クラスライブラリのtoUpper()メソッドを使用して簡単に実行できます。しかし、このプログラムでは、大文字の文字のASCII値を計算することによってこれを実行します。アルゴリズムは次のとおりです。 アルゴリズム START Step-1: Declare the array of char Step-2: Check ASCII value of uppercase characters which must grater than A and lesser