21xrx.com
2024-09-20 00:53:56 Friday
登录
文章检索 我的文章 写文章
C++字符串去重函数
2023-07-10 13:29:18 深夜i     --     --
C++ 字符串 去重 函数

在许多的C++项目中,字符串去重是一个十分常见的需求。然而,如果要手动实现字符串去重的功能,可能需要复杂的算法和代码实现。为了方便程序员实现字符串去重的功能,C++中提供了string的内置函数和一些STL容器可以方便地对字符串进行去重操作。

首先,我们可以使用STL容器set来去重一个字符串。set是一个有序的集合,其中每个元素都插入了,但是只保留了一个副本。这就完美满足了我们对字符串去重的需求。下面是使用set进行字符串去重的示例代码:


#include <iostream>

#include <string>

#include <set>

using namespace std;

string deduplicate(string str) {

  set<char> s;

  string result;

  for (int i = 0; i < str.size(); ++i) {

   if (s.find(str[i]) == s.end()) {

     s.insert(str[i]);

     result += str[i];

   }

  }

  return result;

}

int main() {

  string str = "Hello, World!";

  string dedupedStr = deduplicate(str);

  cout << dedupedStr << endl;

  return 0;

}

在上面的示例代码中,我们定义了一个函数deduplicate(),它接受一个字符串作为参数,并返回去重后的字符串。函数内部使用set来去重字符串,并将去重后的字符拼接成一个新的字符串返回。

除了使用set外,我们还可以使用string的erase()和unique()函数来去重一个字符串。下面是使用erase()和unique()函数进行字符串去重的示例代码:


#include <iostream>

#include <string>

#include <algorithm>

using namespace std;

string deduplicate(string str) {

  str.erase(unique(str.begin(), str.end()), str.end());

  return str;

}

int main() {

  string str = "Hello, World!";

  string dedupedStr = deduplicate(str);

  cout << dedupedStr << endl;

  return 0;

}

在上面的示例代码中,我们定义了一个函数deduplicate(),它接受一个字符串作为参数,并返回去重后的字符串。函数内部使用string的erase()和unique()函数来对字符串进行去重。unique()函数在查找相邻的重复元素时使用了STL中的相邻元素去重算法,并返回去重后的尾部迭代器。我们再使用erase()函数来从字符串中删除所有重复元素。

总而言之,C++ 中提供了多种方式来实现字符串去重的功能。我们可以通过使用STL容器set或使用string的erase()和unique()函数来对字符串进行去重操作。这为我们在实际项目中使用和处理字符串提供了便利。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复