Write a program to accept a string and check whether the string is unique or not
Answers
import java.util.Scanner;
public class UniqueString {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter input: ");
String input = scanner.nextLine();
int[] count = new int[256];
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
count[ch]++;
}
boolean uniqueString = true;
for (int i = 0; i < 256; i++) {
if (count[i] > 1) {
uniqueString = false;
break;
}
}
if (uniqueString) {
System.out.println("Unique string");
} else {
System.out.println("Not a unique string");
}
}
}
Sample Outputs
1.Enter input: applications
2.Not a unique string
1.Enter input: computer
2.Unique string
import java.util.Scanner;
public class KboatUniqueString
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = in.nextLine();
str = str.toUpperCase();
int len = str.length();
int c = 0;
int i;
for ( i = 0; i < len; i++)
{
char ch = str.charAt(i);
}
for (j = i + 1; j < len; j++)
{
if (ch == str.charAt(j))
{
c++;
}
}
if (c>0)
System.out.println("Unique String");
else
System.out.println("Not Unique String");
}
}
for (int i = 0; i < len; i++) {
char ch = str.charAt(i);
for (int j = i + 1; j < len; j++) {
if (ch == str.charAt(j)) {
c++
}
}
}
if (c>0)
System.out.println("Unique String");
else
System.out.println("Not Unique String");
}
}