JAVA中字符串反转

JAVA中字符串反转

分析一下JAVA字符串反转应该怎么解决?
JAVA字符串反转目的就是倒序输出,怎样倒序呢?
1、通过调用现有倒序方法
2、把字符串拆解,然后倒序输出

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@SpringBootTest
@RunWith(SpringRunner.class)
@Slf4j
public class StringReverse {

    static String str = "abcd1234";

    @Test
    public void test1(){
        //StringBuffer/StringBuilder
        String newStr = new StringBuffer(str).reverse().toString();
        log.info("newStr = {}", newStr);
    }
    
    @Test
    public void test2(){
        String newStr = "";
        String[] strs = str.split("");
        for (String s1 : strs
             ) {
            newStr = s1 + newStr;
        }
        log.info("newStr = {}", newStr);
    }

    @Test
    public void test3(){
        String newStr = "";
        for (int i = 0; i < str.length(); i++) {
            newStr = str.charAt(i) + newStr;
        }

        log.info("newStr = {}", newStr);
    }

    @Test
    public void test4(){
        char[] chars = str.toCharArray();
        String newStr = "";
        for (char c : chars) {
            newStr = c + newStr;
        }

        log.info("newStr = {}", newStr);
    }

说明:test1()方法是通过调用Java类内部实现的反转方法
test2/3/4()方法是通过字符串拆解,倒序输出

你可能感兴趣的:(Java)