我想实现一种只反转句子中的字母25000rs for 1 LCD
而不是数字或特殊字符后返回字符串的方法。逆转必须逐字进行。例如:对于25000sr rof 1 DCL
,应为public class Main {
static String reverseWords(String inputString) {
String[] words = inputString.split(" ");
String reverseString = "";
for (int i = 0; i < words.length; i++)
{
String word = words[i];
String reverseWord = "";
for (int j = word.length()-1; j >= 0; j--)
{
reverseWord = reverseWord + word.charAt(j);
}
reverseString = reverseString + reverseWord + " ";
}
return reverseString;
}
public static void main(String[] args)
{
String str1 = "1 cup of hot coffee costs 8.00, whereas cold coffee costs 45.00.";
System.out.println(reverseWords(str1));
String str2 = "It Costs 25000rs for 1 LCD Projector.";
System.out.println(reverseWords(str2));
String str3 = "8990.33";
System.out.println(reverseWords(str3));
}
}
。
com.google.firebase:firebase-ads:17.1.3
1个eeffoc stsoc 8.00,saerehw dloc eeffoc stsoc 45.00。
stsoC 25000sr rof 1 DCL rotcejorP。
8990.33
1个eeffoc stsoc,00.8的serehw dloc eeffoc stsoc .00.54
stsoC sr00052 rof 1 DCL .rotcejorP
33.0998
答案 0 :(得分:2)
您只是在空格字符处进行拆分,这使每个非空格字符序列都成为一个“单词”。
此任务是正则表达式Matcher
的appendReplacement
/ appendTail
循环的典型用例,当预期的替换逻辑对于简单的{ String
上的{3}}:
static final Pattern WORD = Pattern.compile("\\pL+"); // class "L" means "letter"
static String reverseWords(String inputString) {
Matcher m = WORD.matcher(inputString);
if(!m.find()) return inputString;
StringBuffer sb = new StringBuffer(inputString.length());
do {
m.appendReplacement(sb, new StringBuilder(m.group()).reverse().toString());
} while(m.find());
return m.appendTail(sb).toString();
}
(从Java 9开始,该API还支持使用StringBuilder
代替StringBuffer
。
但是在这种特定情况下,操作也可以稍微提高效率:
static String reverseWords(String inputString) {
Matcher m = WORD.matcher(inputString);
if(!m.find()) return inputString;
StringBuilder sb = new StringBuilder(inputString);
do {
for(int ix1 = m.start(), ix2 = m.end() - 1; ix1 < ix2; ix1++, ix2--) {
sb.setCharAt(ix1, inputString.charAt(ix2));
sb.setCharAt(ix2, inputString.charAt(ix1));
}
} while(m.find());
return sb.toString();
}