user6750923 user6750923 - 2 months ago 9
Java Question

Separate specific words from a string in java

Is there any way to split the words from a string in

java
?.

String my ="StackOverFlow PF Apple FT Laptop HW."


PF = Platform, FT = Fruit, HW = Hardware.

The expected output should be

StackOverFlow is a Platform.
Apple is a Fruit.
Laptop is a hardware.


I am doing in this way:

String[] words = my.split(" ");
for(int u=0 ; u<words.length ; u++){
System.out.println( words(u));
}

Answer
public class StackOverflow {

    public static void main(String[] args) {
        // Fields
        String myString = "StackOverFlow PF Apple FT Laptop HW";

        String[] tokens = myString.split(" ");

        for (int i = 0; i < tokens.length; i++) {
            System.out.print(tokens[i]);
            // Every other token
            if (i % 2 == 0) {
                System.out.print(" is a " + convert(tokens[i + 1]));
                i++;
            }
            System.out.println();
        }

    }

    /**
     * convert method turns the abbreviations into long form
     */
    private static String convert(String s) {
        String str;
        switch (s) {
            case "PF":
                str = "Platform";
                break;
            case "FT":
                str = "Fruit";
                break;
            case "HW":
                str = "Hardware";
                break;
            default:
                str = "Unknown";
                break;
        }
        return str;
    }

}