java实现字符串反转
程序员文章站
2024-02-22 14:21:04
本文实例为大家分享了java字符串反转的具体代码,供大家参考,具体内容如下
import java.util.stack;
public class str...
本文实例为大家分享了java字符串反转的具体代码,供大家参考,具体内容如下
import java.util.stack; public class stringreverse { // 使用内置类(stringbuilder或stringbuffer) public static string reverse1(string s) { // stringbuilder strbuilder = new stringbuilder(s); // string ret = strbuilder.reverse().tostring(); stringbuffer strbuf = new stringbuffer(s); string ret = strbuf.reverse().tostring(); return ret; } // 有左到右 拼接字符串 public static string reverse2(string s) { string ret = ""; for (int i = 0; i < s.length(); ++i) { ret = s.charat(i) + ret; } return ret; } // 从右到左 拼接字符串 public static string reverse3(string s) { string ret = ""; for (int i = s.length() - 1; i >= 0; --i) { ret += s.charat(i); } return ret; } public static string reverse4(string s) { string ret = ""; char[] chararr = s.tochararray(); int len = chararr.length; for (int i = 0; i < len / 2; ++i) { char tmp = chararr[i]; chararr[i] = chararr[len - 1 - i]; chararr[len - 1 - i] = tmp; } ret = new string(chararr); return ret; } // 使用异或 public static string reverse5(string s) { string ret = ""; char[] chararr = s.tochararray(); int begin = 0, end = chararr.length - 1; while (begin < end) { chararr[begin] = (char) (chararr[begin] ^ chararr[end]); chararr[end] = (char) (chararr[begin] ^ chararr[end]); chararr[begin] = (char) (chararr[begin] ^ chararr[end]); begin++; end--; } ret = new string(chararr); return ret; } // 使用栈 public static string reverse6(string s) { string ret = ""; stack<character> stack = new stack<character>(); for (int i = 0; i < s.length(); ++i) { stack.push(s.charat(i)); } while (!stack.isempty()) { ret += stack.pop(); } return ret; } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。