I have a String which includes special characters. and i want to print them but not the duplicate ones.
Input String s="&*$%) )_@*% &)((("
Ouput ="&*$%)_@("
I have a String which includes special characters. and i want to print them but not the duplicate ones.
Input String s="&*$%) )_@*% &)((("
Ouput ="&*$%)_@("
Here is a C++ version, in which you can make use of bitset to keep track of unique characters already seen.
#include <iostream>
#include <string>
#include <bitset>
bool IsSpecialChar(const unsigned char& c) {
// your treatment to decide if the character is "special"
return (c < 'a' || c > 'z')
&& (c < 'A' || c > 'Z')
&& (c < '0' || c > '9')
&& (c != ' ');
}
std::string StripDuplicates(const std::string& str) {
std::bitset<256> alreadySeen;
std::string result;
for (const unsigned char& c : str) {
if (!alreadySeen[c] && IsSpecialChar(c)) {
result += c;
alreadySeen[c] = true;
}
}
return result;
}
int main(int argc, char * argv[]) {
std::string testString = "aazrr554AZEZAAZZ&*$%) )_@*% &)(((";
std::string result = StripDuplicates(testString);
std::cout << result << std::endl;
}
Edit: If you want to filter the characters you want to keep with respect to them being "special characters" or not, you might want to add that check in the condition just before appending "c" to "result". I edited the code to reflect that.
Taking the answer from Redgis, and using the std::copy_if
algorithm function:
#include <iostream>
#include <string>
#include <bitset>
#include <iterator>
#include <algorithm>
std::string StripDuplicates(const std::string& str) {
std::bitset<256> alreadySeen;
std::string result;
std::copy_if(str.begin(), str.end(), std::back_inserter(result),
[&](char ch)
{bool seen = alreadySeen[static_cast<unsigned char>(ch)];
alreadySeen.set(ch); return !seen;});
return result;
}
int main(int argc, char * argv[]) {
std::string testString = "&*$%) )_@*% &)(((";
std::string result = StripDuplicates(testString);
std::cout << result << std::endl;
}
Output:
&*$%) _@(
In java first we need to add these characters to HashSet(HashSet is a list which keeps only unique values), then we will use string builder to create a string using these unique values and that's it you can check the code yourself
import java.util.*;
class Main {
public static void main(String[] args) {
String ss = "&*$%) )_@*% &)(((";
Set<Character> set = new HashSet<>();
StringBuilder output
= new StringBuilder();
for (int i = 0; i < ss.length(); i++) {
set.add(ss.charAt(i));
}
for (Character c : set) {
output.append(c);
}
System.out.println(output);
}
}