我从edittext中获取用户输入,将其反转,然后在textview中输出。除了输入的字符串输出(例如StackOverflow is a community of awesome programmers!
变为!programmers awesome of community a is StackOverflow
)之外,一切都正常。
现在我想:
当字符串倒转时,将第一个字母大写:Programmers awesome of community a is StackOverflow
让感叹号或任何其他标点符号放在结尾而不是开头。我们的例子应该是:programmers awesome of community a is StackOverflow !
我使用下面的代码来反转字符串:
String[] nowTyping = input.getText().toString().split(" ");
ArrayList<String> wordArray = new ArrayList<>();
for (String word : nowTyping) {
wordArray.add(0, word);
}
String invertedSentence = TextUtils.join(" ", wordArray);
output.setText(invertedSentence);
我已经试过把第一个字母大写,但似乎不起作用。
谢谢你的时间。
最佳答案
试试这样的
String[] nowTyping = "It is broken!".split(" ");
ArrayList<String> wordArray = new ArrayList<>();
ArrayList<String> symbolsArray = new ArrayList<>();
int cnt=0;
for (int j=nowTyping.length-1 ;j >=0;j--) {
String word = nowTyping[j];
if (word.length()>0) {
word = word.toLowerCase();
char firstChar = word.charAt(0);
if (cnt == 0) {
boolean isFirstCharFounded = false;
for (int i = 0; i < word.length(); i++) {
if (!isFirstCharFounded&&Character.isAlphabetic(word.charAt(i))) {
firstChar = word.charAt(i);
isFirstCharFounded = true;
} else if (!(Character.isDigit(word.charAt(i))||Character.isAlphabetic(word.charAt(i)))) {
symbolsArray.add(word.charAt(i) + "");
word = word.replace(word.charAt(i)+"","");
}
}
firstChar = Character.toUpperCase(firstChar);
cnt++;
}
if (word.length()>=2) {
word = firstChar + word.substring(1);
}
else {
word = firstChar + "";
}
wordArray.add( word);
}
}
String invertedSentence = TextUtils.join(" ", wordArray);
invertedSentence += TextUtils.join("",symbolsArray);