如何将字符串反转

版权声明:转载请注名出处 https://blog.csdn.net/meism5/article/details/89329699

如何将字符串反转?

1、使用StringBuilder的reverse方法
2、不考虑字符串中的字符是否是Unicode编码,自己实现。

代码

        public static void main(String[] args) {
		String str = "ABCDE";
		System.out.println(reverseStringByStringBuilderApi(str));
		System.out.println(reverseString(str));
	}
	
	public static String reverseStringByStringBuilderApi(String str) {
		if (str != null && str.length() > 0) {
			return new StringBuilder(str).reverse().toString();
		}
		return str;
	}
	
	public static String reverseString(String str) {
		if (str != null && str.length() > 0) {
			int len = str.length();
			char[] chars = new char[len];
			for (int i = len - 1; i >= 0; i--) {
				chars[len - 1 - i] = str.charAt(i);
			}
			return new String(chars);
		}
		return str;
	}

猜你喜欢

转载自blog.csdn.net/meism5/article/details/89329699
今日推荐