Cara paling gampang kanggo Mbalikke String ing Jawa

Mbalikke senar minangka salah sawijining pitakon sing paling asring ditakokake ing wawancara teknis Java. Pewawancara bisa uga njaluk sampeyan nulis macem-macem cara kanggo mbalikke senar, utawa bisa uga njaluk sampeyan mbalikke senar tanpa nggunakake metode internal, utawa bisa uga njaluk sampeyan mbalikke senar nggunakake rekursi.

Ing ngisor iki ana macem-macem cara sing bisa digunakake kanggo mbalikke string ing Jawa.



String Reverse ing Jawa, Cara Paling gampang

Cara paling gampang kanggo mbalikke senar ing Jawa yaiku nggunakake reverse() fungsi saka StringBuilder kelas.


Tuladha:

package io.devqa.tutorials; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class ReverseString {
String reverse(String inputString) {
return new StringBuilder(inputString).reverse().toString();
}
@Test
public void testAWord() {
assertEquals('tobor', new ReverseString().reverse('robot'));
} }

Gegandhengan:




String Reverse nggunakake Recursion

Cara liya kanggo mbalikke senar ing jawa yaiku nggunakake rekursi lan nggunakake charAt() cara kanggo String kelas



Tuladha:

import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class ReverseString {
String reverse(String inputString) {

StringBuilder reverseStringBuilder = new StringBuilder();

for(int i = inputString.length() - 1; i>=0; i--){

reverseStringBuilder.append(inputString.charAt(i));
}

return reverseStringBuilder.toString();
}
@Test
public void testAWord() {
assertEquals('tobor', new ReverseString().reverse('robot'));
} }

Variasi saka ndhuwur yaiku nggunakake toCharArray() lan muter liwat karakter, kayata:

import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class ReverseString {
String reverse(String inputString) {
String outString = '';
for(char c : inputString.toCharArray()) {

outString = c + outString;
}
return outString;
}
@Test
public void testAWord() {
assertEquals('tobor', new ReverseString().reverse('robot'));
} }


String Reverse ing Jawa 8

import org.junit.jupiter.api.Test; import java.util.stream.Collectors; import java.util.stream.IntStream; import static org.junit.jupiter.api.Assertions.assertEquals; class ReverseString {
String reverse(String inputString) {
return IntStream.range(0, inputString.length())

.mapToObj(x-> inputString.charAt((inputString.length()-1) - x))

.map(character -> String.valueOf(character))

.collect(Collectors.joining(''));
}
@Test
public void testAWord() {
assertEquals('tobor', new ReverseString().reverse('robot'));
} }