Indlela elula yokuguqula intambo eJava

Ukubuyisa umucu ngenye yemibuzo ebuzwa njalo kwinhlolokhono yezobuchwepheshe yeJava. Ababuzayo bangakucela ukuthi ubhale izindlela ezahlukahlukene zokubuyisela emuva intambo, noma bangakucela ukuthi uhlehlise intambo ngaphandle kokusebenzisa izindlela ezakhelwe ngaphakathi, noma bangakucela nokuthi uhlehlise intambo usebenzisa ukuphindeka.

Ngezansi kunezindlela ezahlukahlukene ongazisebenzisa ukubuyisela emuva intambo kuJava.

Reverse String eJava, Indlela Elula Kakhulu

Indlela elula yokuguqula intambo kuJava ukusebenzisa eyakhelwe ngaphakathi reverse() ukusebenza kwe StringBuilder isigaba.

Isibonelo:

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'));
} }

Okuhlobene:

Reverse String usebenzisa i-Recursion

Enye indlela yokuhlehlisa intambo kuJava ukusebenzisa ukuphindaphinda nokusebenzisa i- charAt() indlela ye- String isigaba



Isibonelo:

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'));
} }

Ukuhluka kwalokhu okungenhla ukusebenzisa toCharArray() bese uqaqa izinhlamvu, isibonelo:

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'));
} }

Reverse String ku Java 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'));
} }