首頁  >  文章  >  後端開發  >  檢查字串是否包含連續的字母,並且每個字母只出現一次

檢查字串是否包含連續的字母,並且每個字母只出現一次

WBOY
WBOY轉載
2023-09-08 13:57:031124瀏覽

檢查字串是否包含連續的字母,並且每個字母只出現一次

Introduction

在C 中,字串是一系列的字符,這些字符可以是不同的或重複的。連續的字符是同時出現的字符,它們之間的差值為1。例如,字元a和b是連續的,因為它們一起出現。然而,字元m和o在它們的位置上有一個差值為2,使它們不是連續的。

在本文中,我們將開發一段程式碼,將以字串作為輸入,並在字串中的所有字元連續時顯示true。讓我們看下面的範例以更好地理解這個主題

Sample Example

範例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.

##Syntax

sort()

的翻譯為:

sort()

sort(str.begin(), str.end())

C 中的sort()方法用於將字串中的字元按照從開始到結束的順序進行增序排列。

參數

str - The input string

end - 字串中最後出現的字元

begin-字串中第一個出現的字元

length()

的翻譯為:

length()

The length() method in C is used to compute the number of characters in the string.

str.length()

參數

str - The input string

演算法

  • 接受一個輸入字串,str作為輸入。

  • The input string is sorted using the sort() method.

  • An iteration of the string is performed, using the for loop i.

  • The length of the string is computed using the length() method and stored in len variable.

  • #在字串上執行for迴圈迭代,i是進行的迭代。

  • 每次擷取第ith, ch和第i-1th, ch1位置的字元。

  • If the difference between these two characters is not equal to 1, then a boolean false value is returned

  • #If all the corresponding characters satisfy the required condition, then the boolean value - true is returned.

  • #這個值以布林標誌的形式傳回,儲存在變數res中。如果它的值為true,則列印出包含連續字元的字串。

Example

以下C 程式碼片段用於輸入一個範例字串,並計算字串中出現的所有字元是否連續。

//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

Conclusion

字串中不斷出現的字元是同時出現的字母。可以透過對字串從開始到結束進行排序來實現。連續位置上的字元可以輕鬆地進行比較,並檢查它們之間相差多少個位置。這可以用來捕捉字串是否是連續的資訊。

以上是檢查字串是否包含連續的字母,並且每個字母只出現一次的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除