public class Reverse {
public static void main(String[] args) {
final String str = "to be or not to be";
final String[] array = str.split(" ");
for(String s:array){
final StringBuilder builder = new StringBuilder();
System.out.print(builder.append(s).reverse()+ " ");
}
}
}
首先利用空格拆分字符串得到一个数组,再用循环,并用一个方法倒置字符串,需要使用的这两个方法都可以在java api中的String类中查找到
stringbuffer类有字符串翻转的reverse方法
Stack数据结构后进先出,自然而然就翻转了
实在不行两个数组,一个是原字符串,一个从数组末尾开始一个字符一个字符存
String str = "113@ ere qqq yyui",写出这个字符串的子串。
public static void main(String[] args) throws Exception {
String s = "113@ ere qqq yyui";
s=s.replaceAll("[^a-zA-Z 0-9]", "");
for (String str: s.split(" ")) {
System.out.println(str);
}
编写一个程序,将下面的一段文本中的各个单词的字母顺序翻转,
“To be or not to be",将变成"oT eb ro ton ot eb."。
//末尾标点是不是不要反转?
s = "To be or not to be.";//"oT eb ro ton ot eb."。
StringBuffer sBuffer = new StringBuffer();
for (String str: s.split("//s")) {
char punctuate=' ';
char[] chars = str.toCharArray();
for (int i = chars.length-1;i>=0;i--) {
if (i==chars.length-1 && !Character.isLetter(chars[i])) {
punctuate = chars[i];
continue;
}
sBuffer.append(chars[i]);
}
sBuffer.append(punctuate);
}
System.out.println(sBuffer);
}
顶
1
踩