Jump to content

Determine if a string has all unique characters: Difference between revisions

Added C++ solution
(Added Prolog)
(Added C++ solution)
Line 668:
"4444 444k" - Length 9 - Contains the following duplicate characters :
'4' (0x34) at positions : 1 2 3 4 6 7 8
</pre>
 
=={{header|C++}}==
<lang cpp>#include <iostream>
#include <string>
 
void string_has_repeated_character(const std::string& str)
{
size_t len = str.length();
std::cout << "input: \"" << str << "\", length: " << len << '\n';
bool unique = true;
for (size_t i = 0; i < len && unique; ++i)
{
for (size_t j = i + 1; j < len; ++j)
{
if (str[i] == str[j])
{
std::cout << "String contains a repeated character.\n";
std::cout << "Character '" << str[i]
<< "' (hex " << std::hex << static_cast<unsigned int>(str[i])
<< ") occurs at positions " << std::dec << i + 1
<< " and " << j + 1 << ".\n";
unique = false;
break;
}
}
}
if (unique)
std::cout << "String contains no repeated characters.\n";
std::cout << '\n';
}
 
int main()
{
string_has_repeated_character("");
string_has_repeated_character(".");
string_has_repeated_character("abcABC");
string_has_repeated_character("XYZ ZYX");
string_has_repeated_character("1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ");
return 0;
}</lang>
 
{{out}}
<pre>
input: "", length: 0
String contains no repeated characters.
 
input: ".", length: 1
String contains no repeated characters.
 
input: "abcABC", length: 6
String contains no repeated characters.
 
input: "XYZ ZYX", length: 7
String contains a repeated character.
Character 'X' (hex 58) occurs at positions 1 and 7.
 
input: "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ", length: 36
String contains a repeated character.
Character '0' (hex 30) occurs at positions 10 and 25.
 
</pre>
 
1,777

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.