句子中的字符应该颠倒而不是单词
我尝试了以下代码
public class ReverseWords {
public static void main(String[] args) {
ReverseWords obj = new ReverseWords();
obj.reverseWordInMyString("It Costs 25000rs for 1 LCD Projector");
obj.reverseWordInMyString("8990.33 ");
}
public void reverseWordInMyString(String str)
{
String[] words = str.split(" ");
String reversedString = "";
for (int i = 0; i < words.length; i++)
{
String word = words[i];
String reverseWord = "";
boolean numeric = true;
try {
Double num = Double.parseDouble(word);
} catch (NumberFormatException e) {
numeric = false;
}
if(!numeric) {
for (int j = word.length()-1; j >= 0; j--)
{
reverseWord = reverseWord + word.charAt(j);
}
reversedString = reversedString + reverseWord + " ";
}
else {
reversedString = reversedString + word + " ";
}
}
System.out.println(str);
System.out.println(reversedString);
}
}
我得到的输出是:tststC sr00052 rof 1 DCL rotcejorP
预期输出为:tI stsoC 25000sr rof 1 DCL rotcejorP
答案 0 :(得分:2)
这应该做到。
String str = "It Costs 25000rs for 1 LCD Projector";
StringBuilder sb = new StringBuilder(str);
Matcher m = Pattern.compile("([A-Za-z]+)").matcher(str);
StringBuilder temp = new StringBuilder();
while (m.find()) {
String rev = temp.append(m.group(1)).reverse().toString();
sb.replace(m.start(), m.end(), rev);
temp.setLength(0);
}
String reversed = sb.toString();
System.out.println(reversed);
答案 1 :(得分:1)
npm install
答案 2 :(得分:1)
我不喜欢这种解决方案,因为我总体上不喜欢while循环,但这似乎是逐个字符进行的最干净的方法(请告诉我如何进行改进)。它也应该是最有效的解决方案。我将问题理解为“应颠倒字母字符的顺序”。
public class ReverseWords {
private static void reverse(char[] a, int left, int right) {
right --;
while (left < right) {
char temp = a[left];
a[left] = a[right];
a[right] = temp;
left++;
right--;
}
}
public static void main(String[] args) {
char[] a = "It Costs 25000rs for 1 LCD Projector".toCharArray();
int i = 0;
while (i < a.length) {
if (!Character.isAlphabetic(a[i])) {
i++;
continue;
}
int j = i + 1;
while (j < a.length && Character.isAlphabetic(a[j])) {
j++;
}
reverse(a, i, j);
i = j;
}
System.out.println(new String(a));
}
}
答案 3 :(得分:-1)
使用正则表达式如何?匹配[a-zA-Z]*[^(\d*)]
之类的东西会隔离您的Alpha字符而不会与您的数字匹配。根据项目的要求,该语句可能需要稍作修改,但应该可以使您走上正确的轨道。