正在 java 外,否以经由过程下列六种法子来反转字符串:利用 stringbuilder利用 chararray利用 collections.reverse()利用迭代器运用位运算符利用递回

java怎么反转字符串

奈何应用 Java 反转字符串

正在 Java 外,否以经由过程下列多少种办法来反转字符串:

1. 运用 StringBuilder

String originalString = "Hello World";
StringBuilder reversedString = new StringBuilder();

for (int i = originalString.length() - 1; i >= 0; i--) {
    reversedString.append(originalString.charAt(i));
}

System.out.println(reversedString.toString());
登录后复造

两. 应用 CharArray

String originalString = "Hello World";
char[] chars = originalString.toCharArray();

for (int i = 0; i <p><strong>3. 利用 Collections.reverse()</strong></p><pre class="brush:php;toolbar:false">String originalString = "Hello World";
List<character> chars = new ArrayList();

for (char c : originalString.toCharArray()) {
    chars.add(c);
}

Collections.reverse(chars);

StringBuilder reversedString = new StringBuilder();
for (char c : chars) {
    reversedString.append(c);
}

System.out.println(reversedString.toString());</character>
登录后复造

4. 利用迭代器

String originalString = "Hello World";
List<character> chars = new ArrayList();

for (char c : originalString.toCharArray()) {
    chars.add(c);
}

Iterator<character> iterator = chars.iterator();
while (iterator.hasNext()) {
    char c = iterator.next();
    iterator.remove();
    chars.add(0, c);
}

StringBuilder reversedString = new StringBuilder();
for (char c : chars) {
    reversedString.append(c);
}

System.out.println(reversedString.toString());</character></character>
登录后复造

5. 应用位运算符

String originalString = "Hello World";
int n = originalString.length();
char[] chars = originalString.toCharArray();

for (int i = 0; i <p><strong>6. 应用递回</strong></p><pre class="brush:php;toolbar:false">String originalString = "Hello World";

public static String reverseStringRecursively(String str) {
    if (str == null || str.length() == 0) {
        return str;
    }
    return reverseStringRecursively(str.substring(1)) + str.charAt(0);
}

String reversedString = reverseStringRecursively(originalString);
System.out.println(reversedString);
登录后复造

以上即是java如果反转字符串的具体形式,更多请存眷萤水红IT仄台此外相闭文章!

点赞(34) 打赏

评论列表 共有 0 条评论

暂无评论

微信小程序

微信扫一扫体验

立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部