In: Computer Science
Write a java method that takes a string and returns an array of int that contains the corresponding alphabetic order of each letter in the received string:
An illustration:
the method takes: "Sara"
the method returns: {4,1,3,2}
another illustration:
the method takes: "hey"
the method returns: {2,1,3}
Code:
import java.util.*;
public class alphabetOrder
{
static int[] findOrder(String str)
{
// Storing the size of the string
int strSize = str.length();
// This value is used to keep track of order of the character
int value = 0;
// Declaring an array whose size is same as the size of the string
int order[] = new int[strSize];
// Iterating over ASCII values of lowercase alphabets
for (int i = 97; i <= 122; i++)
{
// Iterating over the string
for (int j = 0; j < strSize; j++)
{
// If the ASCII value of character at index j in the string str is equal to i
if ((int) str.charAt(j) == i)
{
// Increment the value by 1
value++;
// Storing the value at index j in the array
order[j] = value;
}
}
}
// Returning the order array
return order;
}
public static void main(String[] args)
{
// Creating an scanner object
Scanner inp = new Scanner(System.in);
// Prompting the user to enter the string
System.out.print("Enter the string: ");
// Reading the string from the user
String str = inp.nextLine().toLowerCase();
// Storing the int array returned by the findOrder method
int result[] = findOrder(str);
// Printing the result array
System.out.println(Arrays.toString(result));
// Closing the scanner object
inp.close();
}
}
Sample Output: