Megaetron
Megaetron

Reputation: 1192

How to detect the letters in a String and switch them?

How to detect the letters in a String and switch them?

I thought about something like this...but is this possible?

//For example:
String main = hello/bye;

if(main.contains("/")){
    //Then switch the letters before "/" with the letters after "/"
}else{
    //nothing
}

Upvotes: 2

Views: 179

Answers (5)

Darien
Darien

Reputation: 1

Also you can use StringTokenizer to split the string.

String main = "hello/bye"; StringTokenizer st = new StringTokenizer(main,"\");

String part1 = st.nextToken(); String part2 = st.nextToken();

String newMain = part2 + "\" + part1;

Upvotes: 0

Maria Gheorghe
Maria Gheorghe

Reputation: 629

you can use string.split(separator,limit)

limit : Optional. An integer that specifies the number of splits, items after the split limit will not be included in the array

String main ="hello/bye";
if(main.contains("/")){
    //Then switch the letters before "/" with the letters after "/"
    String[] parts  = main.split("/",1);

    main = parts[1] +"/" + parts[0] ; //main become 'bye/hello'
}else{
    //nothing
}

Upvotes: 0

Johan Tidén
Johan Tidén

Reputation: 695

You can use String.split e.g.

String main = "hello/bye";
String[] splitUp = main.split("/"); // Now you have two strings in the array.

String newString = splitUp[1] + "/" + splitUp[0];

Of course you have to also implement some error handling when there is no slash etc..

Upvotes: 3

TheLostMind
TheLostMind

Reputation: 36304

Well, if you are interested in a cheeky regex :P

public static void main(String[] args) {
        String s = "hello/bye"; 
        //if(s.contains("/")){ No need to check this
            System.out.println(s.replaceAll("(.*?)/(.*)", "$2/$1")); // () is a capturing group. it captures everything inside the braces. $1 and $2 are the captured values. You capture values and then swap them. :P
        //}

    }

O/P :

bye/hello --> This is what you want right?

Upvotes: 8

M A
M A

Reputation: 72844

Use String.substring:

main = main.substring(main.indexOf("/") + 1)
       + "/"
       + main.substring(0, main.indexOf("/")) ;

Upvotes: 3

Related Questions