java:
题目描述:
- 给定一个字符串,将其中的每一个单词进行翻转并输出翻转后的字符串
- 单词的定义为“连续的由字母组成的子串”,例如"abc-1de/fg"的单词有3个,为["abc", "de", "fg"]
示例:
输入:"abc-1de/fg"
输出:"cba-1ed/gf"
函数体:
public String wordReverse(String inputStr) {
}
public String wordReverse(String inputStr) {
// String str = "abc-1de/fg";
if ((inputStr == null || inputStr.length() <= 0)) {
return "";
}
StringBuilder builder = new StringBuilder();
int prevStart = -1;
Pattern pattern = Pattern.compile("[a-zA-Z]+");
Matcher matcher = pattern.matcher(inputStr);
while (matcher.find()) {
// 添加非单词
if (prevStart > -1) {
String prev = inputStr.substring(prevStart, matcher.start());
builder.append(prev);
}
//添加反转后的单词
String word = matcher.group();
for (int i = word.length() - 1; i >= 0; i--) {
builder.append(word.charAt(i));
}
prevStart = matcher.end();
}
// System.out.println(builder.toString());
return builder.toString();
}
网友评论