C++ 对一个包含字母和数字的字符串进行排序,使得字母和数字的位置保持不变
介绍
在本教程中,我们介绍一种排序包含字母和数字的字符串的方法,使得字母和数字的位置保持不变。在这种方法中,我们使用C++函数,并输入一个包含字符和数字的字符串。生成不改变字母和数字位置的字符串。新排序的字符串按字母顺序包含打乱的字符,而数字的排列将保持它们的位置不变。
示例1
String = “”tutorials43points”
Output = aiilnoopr34sstttu
在上面的示例中,输入字符串被重新排列,但不改变数字32的位置。字符按字母顺序排序,数字按递增顺序排列。
示例2
String = “India16love”
Output = adeii16lnov
在上面的示例中,输入字符串以字符India开头,并以字符“love”结尾,数字16位于2个字符之间。按字母顺序对这两个字符进行排序,但不改变数字16的位置。
我们使用C++编程概念和一些库函数,如下所示:
- isdigit()
-
isalpha()
-
end()
-
begin()
-
sort()
语法
isdigit(int value);
isdigit() 是定义在cctype头文件中的库函数,用于字符。它检查输入字符串是否包含数字。如果字符串不包含数字,则返回none,否则返回0。
isalpha(int value);
isalpha() 在cctype头文件中定义,用于字符。它用于检查传递的参数是否包含字母。如果参数中没有字母,则返回0,否则返回非零值。
end() 函数用于将指针传递给输入字符串的最后一个元素。它在C ++标准库中定义。
begin() 函数将指针传递给参数的起始元素。
sort() 函数在C ++中是一个内置的库函数,用于将输入元素排序或排列为增加的顺序。
步骤
- 获取一个输入字符串
-
使用isdigit()函数在输入字符串中查找数字,并将它们存储在单独的字符串中。
-
使用alpha()函数在输入的字母数字字符串中查找字母,并将它们存储在单独的字符串中。
-
使用sort()函数分别对两个字符串进行排序。
-
在迭代这两个排序好的字符串的同时将它们合并。
-
打印结果字符串。
示例
我们取一个包含字符和数字的输入字符串“tutorials43point”。这种方法在不改变字符和数字的位置的情况下对字符串进行排序。
#include <iostream>
#include <algorithm>
#include <cctype>
int main(){
std::string s = "tutorials43point";
std::string nums, chars;
// Separate the alphanumeric string into numbers and alphabets
for (char ch : s) {
if (isdigit(ch)){
nums += ch;
}
else if (isalpha(ch)){
chars += ch;
}
}
// Sort the alphabets and numbers separately
std::sort(chars.begin(), chars.end());
std::sort(nums.begin(), nums.end());
// Merge the sorted alphabets and numbers back into the original string
int i = 0, j = 0;
for (char& ch : s){
if (isdigit(ch)){
ch = nums[j++];
}
else if (isalpha(ch)){
ch = chars[i++];
}
}
std::cout << "The new string is : "<< s << std::endl;
return 0;
}
输出
The new string is : aiilnoopr34stttu
结论
在本文中,我们使用C++库函数实现了一个示例,该示例可以在不改变字母和数字位置的情况下排列给定的字符串。输入字符串字符按字母顺序排列,并以增加的顺序显示数字。该方法使用了不同的库函数,如isdigit()、isalpha()、end()、begin()和sort()。