Sidak
Sidak

Reputation: 29

String in Java : charAt Function use

Reversing a string can be done by concatenating the Original String through a reverse loop (from str.length-1->0)

but why is this not Working Correctly : by adding the character by character from last positon to the 0th position:

int i = 0;
while(i<originalStr.length())
{
    strRev.charAt(i)=originalStr.charAt(str.length()-1-i);
    i++;
}

Upvotes: 1

Views: 255

Answers (3)

Zhivko.Kostadinov
Zhivko.Kostadinov

Reputation: 467

In your test method, best practice is to use triple A pattern:
Arrange all necessary preconditions and inputs.
Act on the object or method under test.
Assert that the expected results have occurred.

@Test
 public void test() {
    String input = "abc";

    String result = Util.reverse(input);

    assertEquals("cba", result);
 }

Upvotes: 0

Vikrant Kashyap
Vikrant Kashyap

Reputation: 6846

strRev.charAt(i) // use to Retrieve what value at Index. Not to Set the Character to the Index.

All we know that String is a immutable class in Java. Each time if you try to modify any String Object it will Create a new one.

eg :- String abc = "Vikrant"; //Create a String Object with "Vikrant"
      
      abc += "Kashyap";    //Create again a new String Object with "VikrantKashyap" 
                          // and refer to abc again to the new Object.
      //"Vikrant" Will Removed by gc after executing  this statement.

Better to Use StringBuffer or StringBuilder to perform reverse Operation. The only Difference between these two class is

A) StringBuffer is a Thread Safe (Synchronized). A little slow because each time need to check Thread Lock.

B) StringBuider is not Thread Safe. So, It gives you much faster Result Because it is Not Synchronized.

There are Several Third Party Jars which provides you a Features like Reverse and Many more String base Manipulation Methods

 import org.apache.commons.lang.StringUtils; //Import Statement

 String reversed = StringUtils.reverse(words);

Upvotes: 2

Arnaud Denoyelle
Arnaud Denoyelle

Reputation: 31225

Strings are immutable in Java. You cannot edit them.

If you want to reverse a String for training purpose, you can create a char[], manipulate it then instantiate a String from the char[].

If you want to reverse a String for professional purpose, you can do it like this :

String reverse = new StringBuilder(originalStr).reverse().toString();

Upvotes: 7

Related Questions