简体   繁体   中英

How to reverse a String after a comma and then print the 1st half of the String Java

For example String grdwe,erwd becomes dwregrdwe

I have most of the code I just have trouble accessing all of ch1 and ch2 in my code after my for loop in my method I think I have to add all the elements to ch1 and ch2 into two separate arrays of characters but I wouldn't know what to initially initialize the array to it only reads 1 element I want to access all elements and then concat them. I'm stumped.

And I'd prefer to avoid Stringbuilder if possible

public class reverseStringAfterAComma{
    public void reverseMethod(String word){   

        char ch1 = ' ';
        char ch2 = ' ';
        for(int a=0; a<word.length(); a++)
        {
            if(word.charAt(a)==',')
            {
                for(int i=word.length()-1; i>a; i--)
                {
                    ch1 = word.charAt(i);
                    System.out.print(ch1);
                }
                for (int j=0; j<a; j++)
                {
                    ch2 = word.charAt(j);
                    System.out.print(ch2);
                }
            }
        }

        //System.out.print("\n"+ch1);
        //System.out.print("\n"+ch2);
    } 
    public static void main(String []args){
        reverseStringAfterAComma rsac = new reverseStringAfterAComma();
        String str="grdwe,erwd";
        rsac.reverseMethod(str);
     }
}

You can use string builder as described here :

First split the string using:

String[] splitString = yourString.split(",");

Then reverse the second part of the string using this:

splitString[1] = new StringBuilder(splitString[1]).reverse().toString();

then append the two sections like so:

String final = splitString[1] + splitString[0];

And if you want to print it just do:

System.out.print(final);

The final code would be:

String[] splitString = yourString.split(",");
splitString[1] = new StringBuilder(splitString[1]).reverse().toString();
String final = splitString[1] + splitString[0];
System.out.print(final);

Then, since you are using stringbuilder all you need to do extra, is import it by putting this at the top of your code:

import java.lang.StringBuilder;

It appears you currently have working code, but are looking to print/save the value outside of the for loops. Just set a variable before you enter the loops, and concatenate the char s in each loop:

String result = "";
for (int a = 0; a < word.length(); a++) {
    if (word.charAt(a) == ',') {
        for (int i = word.length() - 1; i > a; i--) {
            ch1 = word.charAt(i);
            result += ch1;
        }
        for (int j = 0; j < a; j++) {
            ch2 = word.charAt(j);
            result += ch2;
        }
    }
}
System.out.println(result);

Demo

Let propose a solution that doesn't use a StringBuilder

You should knoz there is no correct reason not to use that class since this is well tested

The first step would be to split your String on the first comma found (I assumed, in case there is more than one, that the rest are part of the text to reverse). To do that, we can you String.split(String regex, int limit) .

The limit is define like this

  • If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n and the array's last entry will contain all input beyond the last matched delimiter.
  • If n is non-positive then the pattern will be applied as many times as possible and the array can have any length.
  • If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

Example :

"foobar".split(",", 2) //      {"foobar"}
"foo,bar".split(",", 2) //     {"foo", "bar"}
"foo,bar,far".split(",", 2) // {"foo", "bar,far"}

So this could be used at our advantage here :

String text = "Jake, ma I ,dlrow olleh";
String[] splittedText = text.split( ",", 2 ); //will give a maximum of a 2 length array

Know, we just need to reverse the second array if it exists, using the simplest algorithm.

String result;
if ( splittedText.length == 2 ) { //A comma was found
    char[] toReverse = splittedText[1].toCharArray(); //get the char array to revese
    int start = 0;
    int end = toReverse.length - 1;
    while ( start < end ) { //iterate until needed
        char tmp = toReverse[start];
        toReverse[start] = toReverse[end];
        toReverse[end] = tmp;

        start++; //step forward
        end--; //step back
    }
    result = new String( toReverse ) + splittedText[0];
} 

This was the part that should be done with a StringBuilder using

if ( splittedText.length == 2 ){ 
    result = new StringBuilder(splittedText[1]).reverse().toString() + splittedText[0];
}

And if there is only one cell, the result is the same as the original text

else { //No comma found, just take the original text
    result = text;
}

Then we just need to print the result

System.out.println( result );

hello world, I am Jake

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM