在c++中我想删去字符串中所有0 例如10006552删去0并从小到大排序
时间: 2024-03-02 14:49:21 浏览: 21
您可以先使用`std::remove()`函数来删除字符串中的所有`'0'`字符,然后使用`std::sort()`函数来对剩余的字符进行排序。以下是一个示例代码:
```c++
#include <iostream>
#include <algorithm>
#include <string>
int main() {
std::string str = "10006552";
// 删除所有 '0'
str.erase(std::remove(str.begin(), str.end(), '0'), str.end());
// 对剩下的字符进行排序
std::sort(str.begin(), str.end());
// 输出结果
std::cout << str << std::endl;
return 0;
}
```
在上述代码中,我们使用`std::remove()`函数删除了所有的`'0'`字符,然后使用`std::sort()`函数对字符串进行了排序。最终,输出结果为`12556`,即删除了所有的`'0'`字符,并按从小到大的顺序排序了剩余的字符。
相关问题
再c++中我想删去字符串中的元素,类似00128删去00
您可以使用C++中的字符串操作函数erase()来删除字符串中指定的元素。假设要删除字符串中的"00",可以使用以下代码:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "00128";
string substr = "00";
size_t pos = str.find(substr);
if (pos != string::npos) {
str.erase(pos, substr.length());
}
cout << str << endl;
return 0;
}
```
在上述代码中,首先定义了一个字符串`str`,它的值为"00128"。接着,定义了一个子字符串`substr`,它的值为"00"。然后,使用字符串中的`find()`函数查找子字符串在主字符串中第一次出现的位置,如果找到了,则使用`erase()`函数删除该子字符串。
输出结果为"128",即"00"已经被成功删除了。
c++字符串从小到大排序
可以使用 STL 中的 `sort` 函数对字符串进行从小到大排序。例如:
```c++
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() {
string s = "cba";
sort(s.begin(), s.end());
cout << s << endl; // 输出 abc
return 0;
}
```
在这个例子中,我们使用 `sort` 函数对字符串 `s` 进行排序,函数的参数是字符串的起始地址和结束地址,即 `s.begin()` 和 `s.end()`。排序后,字符串 `s` 的内容变为从小到大排列的字符序列。