在C 中,字串是一系列的字符,這些字符可以是不同的或重複的。連續的字符是同時出現的字符,它們之間的差值為1。例如,字元a和b是連續的,因為它們一起出現。然而,字元m和o在它們的位置上有一個差值為2,使它們不是連續的。
在本文中,我們將開發一段程式碼,將以字串作為輸入,並在字串中的所有字元連續時顯示true。讓我們看下面的範例以更好地理解這個主題
範例1 - str - “pqsr”
輸出 - 是
In this article, we will develop a code to extract the current and the previous character from the string. It is then further checked if the characters differ by position non-equivalent to 1, then the lean fse value.
##Syntaxsort(str.begin(), str.end())
參數
end - 字串中最後出現的字元
begin-字串中第一個出現的字元
length()
str.length()參數
演算法
//including the required libraries #include <bits/stdc++.h> using namespace std; //function to check of characters consecutive bool validateString(string str) { //length of the string int len = str.length(); // sorting the given string sort(str.begin(), str.end()); // Iterate for every index and // check for the condition for (int i = 1; i < len; i++) { //extract characters at the required pos char ch = str[i]; char ch1 = str[i-1]; if (ch-ch1 != 1) //in case characters are not consecutive return false; } //if condition holds return true; } //calling the main method int main() { // 1st example string str = "mpon"; cout << "Input String : " <<str << " \n"; bool res = validateString(str); if (res) cout << "Yes, the string contains only consecutive characters\n"; else cout << "No, the string doesn't contain only consecutive characters.\n"; return 0; }Output
Input String − mpon Yes, the string contains only consecutive characters
以上是檢查字串是否包含連續的字母,並且每個字母只出現一次的詳細內容。更多資訊請關注PHP中文網其他相關文章!