Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Write a genetic method to remove a part of string after a particular character and till a particular character

I am trying to write a generic java method wherein I want to remove a part of a String after a particular character and till a particular character. For e.g. "My name is-A" is the String, then I want a method that should remove String till – or remove String after -. So my expected output here would be "My name is-" or "A". Below is my code.

String p="Free Float Factor-FFF";
        
        char[] s2= p.toCharArray();
        char[] s3;
        int i=0;
        do {
            s3=ArrayUtils.remove(s2, i);
            i++;
        }while((!s2.equals("-"))&&i<s2.length);
        
        System.out.println(new String(s3));

    }

The output I am getting here is Free Float Factor-FF I want either "Free Float Factor-" or "FFF" as the output. I am trying to convert the String into an array and then remove the part of the String till – but it is removing the last character. Slightly confused by this.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It’s unclear how you would decide whether to return the bit before or the bit after. But you can get those two parts using indexOf to find the character, and then use substring to get the portion of the string:

int pos = p.indexOf('-');
String before = p.substring(0, pos);
String after = p.substring(pos+1);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading