首页 > 文章列表 > 检查字符串是否包含连续的字母,并且每个字母只出现一次

检查字符串是否包含连续的字母,并且每个字母只出现一次

字符串 关键词提取: 包含连续的字母 每个字母只出现一次
365 2023-08-28

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 boolean false value is returned.

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 charactersn";
   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

字符串中不断出现的字符是同时出现的字母。可以通过对字符串从开始到结束进行排序来实现。连续位置上的字符可以很容易地进行比较,并检查它们之间相差多少个位置。这可以用来捕捉字符串是否是连续的信息。