0

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);
     }
}
azro
  • 53,056
  • 7
  • 34
  • 70
James
  • 11
  • 3
  • 1
    Any reason to avoid `StringBuilder`? This code currently produces `dwregrdwe` as the output - is that not what you want? If not, can you advise the desired output for an input of `grdwe,erwd`? – achAmháin May 14 '18 at 16:10
  • I don't normally use stringbuilder so I'm just trying to avoid any kind of confusion. It does run but try running either line I commented out only 1 element gets printed. It will only output all in the loop – James May 14 '18 at 16:14
  • So it is actually working fine as is, but you want to print the result outside of the loop? The commented out print statements just print a char, so it will only print one character. – achAmháin May 14 '18 at 16:16
  • Just an advice, if you create a `String` in a loop, you usually want to use a `StringBuilder` ! – AxelH May 20 '18 at 10:46

3 Answers3

1

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;
Trevor Clarke
  • 1,482
  • 1
  • 11
  • 20
  • Ah.. Hmm.. May I suggest you try it. I think that you are making it more complicated by avoiding it... 20+ lines of code vs ~6 – Trevor Clarke May 14 '18 at 16:19
  • @William I for simplicity I have written out the block of code and described how to import stringbuilder. I understand it may be new, but I think that trying to reverse a string with loops is making it more complicated than necessary! Would you try using my solution? – Trevor Clarke May 14 '18 at 16:23
  • 1
    @notyou this is only a preference that doesn't make sense. Unless you start using an array to reverse the text, You should not use a String concatenation to do it. – AxelH May 20 '18 at 10:49
  • Agree with @AxelH, notforyuo preferences are terrible – Jacek Cz May 20 '18 at 14:25
  • See [my answer](https://stackoverflow.com/a/50436931/4391450) about `String.split` to prevent any problem. The behavior is not as simple as you could think ;) – AxelH May 20 '18 at 16:24
  • @AxelH as I mentioned further down, I just gave the OP an option of how to access the result out of the loops, using their code. I didn’t rewrite it for them. – achAmháin May 21 '18 at 11:33
  • @notyou that's not the point here ;-) the point is that some preferences can/should be ignore to provide better solutions. – AxelH May 21 '18 at 11:42
0

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 chars 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

achAmháin
  • 4,176
  • 4
  • 17
  • 40
  • 1
    You know the length of the text to reverse, so use an `char[] instead. Create that many `String` instance just to reverse one is terrible ;) – AxelH May 20 '18 at 10:49
  • Answer has few problems 1) duplicate standard library 2) performace 3) bad style (my personal opinion. mainly because of terrible ignoring basic Java faccts) – Jacek Cz May 20 '18 at 14:24
  • @AxelH and JacekCz , the OP just wanted to have his result outside of the loops, so I just used **his** code to do so. I feel the downvote is quite unwarranted here. – achAmháin May 21 '18 at 11:31
  • I agree with you, the comment is there to mention that this is not a good practice, not a bad answer. (Didn't downvote by the way) – AxelH May 21 '18 at 11:40
  • Ok fair enough. There’s enough good answers anyway here to amend now :) – achAmháin May 21 '18 at 11:42
  • There is nothing to amend ! Correcting the original post is good for an answer. – AxelH May 22 '18 at 10:10
  • @AxelH oops I meant *not* to amend now – achAmháin May 22 '18 at 10:18
0

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

AxelH
  • 14,325
  • 2
  • 25
  • 55