w3resource

C++ String Exercises: Find Unique Character String

C++ String: Exercise-39 with Solution

Write a C++ program that checks whether a given string contains unique characters or not. Return true if the string contains unique characters otherwise false.

Test Data:
("Filename") -> 0
("abc") -> 1

Sample Solution:

C++ Code:

#include <bits/stdc++.h>

using namespace std;

bool test(string word)
{
    for (int i = 0; i < word.length() - 1; i++) {
        for (int j = i + 1; j < word.length(); j++) {
            if (word[i] == word[j]) {
                return false;
            }
        }
    }
    return true;
}

int main()
{
	string str = "Filename";
	cout << "String: " << str;
	cout << "\nCheck said string contains unique characters! " << test(str) << endl; 
	str = "abc";
	cout << "\nString: " << str;
	cout << "\nCheck said string contains unique characters! " << test(str) << endl; 
}

Sample Output:

String: Filename
Check said string contains unique characters! 0

String: abc
Check said string contains unique characters! 1

Flowchart:

Flowchart: Find Unique Character String.

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous C++ Exercise: Remove a specific character from a given string.

Next C++ Exercise: Select lowercase characters from the other string.

What is the difficulty level of this exercise?



Share this Tutorial / Exercise on : Facebook and Twitter

C++ Programming: Tips of the Day

How to replace all occurrences of a character in string?

std::string doesn't contain such function but you could use stand-alone replace function from algorithm header.

#include <algorithm>
#include <string>

void some_func() {
  std::string s = "example string";
  std::replace( s.begin(), s.end(), 'x', 'y'); // replace all 'x' to 'y'
}

Ref: https://bit.ly/3niU71x