Sunday, 3 April 2016

String Manipulation Program-1 in JAVA


Description:

10 digit number: 1234567812
10 digit number in words: ONETWOTHREEFOURFIVESIXSEVENEIGHTONETWO

Constraints:

1) remove duplicate letters in the above string.
2) final string must be in sorted order.

Final String: EFGHINORSTUVWX

Program:

import java.util.Arrays;
import java.util.Scanner;

public class String_Program{
public static boolean ISin(String str, char c) {
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == c) {
return true;
}
}
return false;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter 10 digit number: ");
long n = s.nextLong();
String str = n + "";
String res = "";
String no[] = new String[] { "ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE" };
if (str.length( ) < 10 || str.length( ) > 10) {
System.out.println("Invalid Input");
} else {
for (int i = 0; i < str.length(); i++) {
res = res + no[Integer.parseInt(str.charAt(i) + "")];
}
}
String temp = "";
for (int i = 0; i < res.length(); i++) {
if (!ISin(temp, res.charAt(i))) {
temp = temp + res.charAt(i);
}
}
String r[] = new String[temp.length()];
for (int i = 0; i < r.length; i++) {
r[i] = temp.charAt(i) + "";
}
String rr = "";
Arrays.sort(r);
for (int i = 0; i < r.length; i++) {
rr += r[i];
}
System.out.println(rr);

}
}

Input/Output:

Enter 10 digit number:
1234567812
EFGHINORSTUVWX



0 comments:

Post a Comment