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?



Follow us on Facebook and Twitter for latest update.

C++ Programming: Tips of the Day

Function for C++ struct

A struct is identical to a class except for the default access level (member-wise and inheritance-wise). (and the extra meaning class carries when used with a template)

Every functionality supported by a class is consequently supported by a struct. You'd use methods the same as you'd use them for a class.

struct foo {
int bar;
foo() : bar(3) {}   //look, a constructor
intgetBar() 
  { 
return bar; 
  }
};

foo f;
int y = f.getBar(); // y is 3

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

 





We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook