我有以下代码逐字反转字符串,但我有一个问题,首先可以有人指出如何使它更好的代码?第二,如何在新字符串的开头删除我最终得到的空格.
String str = "hello brave new world"; tStr.reverseWordByWord(str) public String reverseWordByWord(String str){ int strLeng = str.length()-1; String reverse = "",temp = ""; for(int i = 0; i <= strLeng; i++){ temp += str.charAt(i); if((str.charAt(i) == ' ') || (i == strLeng)){ for(int j = temp.length()-1; j >= 0; j--){ reverse += temp.charAt(j); if((j == 0) && (i != strLeng)) reverse += " "; } temp = ""; } } return reverse; }
此刻的短语变为:
olleh evarb wen dlrow
注意新字符串开头的空格.
解决方法
不使用split函数代码看起来像:
public static void reverseSentance(String str) { StringBuilder revStr = new StringBuilder(""); int end = str.length(); // substring takes the end index -1 int counter = str.length()-1; for (int i = str.length()-1; i >= 0; i--) { if (str.charAt(i) == ' ' || i == 0) { if (i != 0) { revStr.append(str.substring(i+1,end)); revStr.append(" "); } else { revStr.append(str.substring(i,end)); } end = counter; } counter--; } System.out.println(revStr); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。