Anusha Anusha - 7 months ago 14
Java Question

Extract a string omitting certain characters in java

This is my string

1 AP(PEAR + ANC)E (CAN anag)

14 EN(T)ICE (NIECE anag)

15 CHIC ("SHEIK" hom)

The string has an answer hidden,
The first string has an answer APPEARANCE and second string has ENTICE
I must extract those particular answer alone from the strings.
I tried to extract those words from it by

String input = "AP(PEAR + ANC)E (CAN anag)";;
String output = input.substring(0, input.indexOf(' '));
System.out.println(output);


Output:

AP(PEAR

As you can see, there is a space after R so the sub-string stops there and so the output. But Is there any way to read till the character 'E'(ie. end of string 'APPEARANCE') ? I want to stop reading if there is a space and if the next character is '(' .

I have another type of string in the same program "EN(T)ICE (NIECE anag)"

String input = "EN(T)ICE (NIECE anag)";
String output = input.substring(0, input.indexOf(' '));
System.out.println(output);


Output:

EN(T)ICE

There is a space after the character 'E' so it successfully gave the full output. Is there any way to get output like this for the first string. ? Any help would be great !!

Answer

Use replaceFirst instead of indexOf and substring.

    String[] inputs = {
        "AP(PEAR + ANC)E (CAN anag)",
        "EN(T)ICE (NIECE anag)", 
        "CHIC (\"SHEIK\" hom)"};
    for (String s : inputs) {
        String output = s.replaceFirst(" \\(.*", "");
        System.out.println(output);
    }

results:

AP(PEAR + ANC)E
EN(T)ICE
CHIC