我正在尝试在字符串中找到第n个单词。我不允许使用StringToknizer
课程中的split
或String
方法。
我现在意识到我可以使用空格作为分隔符。唯一的问题是我不知道如何找到第一个空格的位置。
public static String pick(String message, int number){
String lastWord;
int word = 1;
String result = "haha";
for(int i=0; i<message.length();i++){
if(message.charAt(i)==' '){enter code here
word++;
}
}
if(number<=word && number > 0 && number != 1){//Confused..
int space = message.indexOf(" ");//improve
int nextSpace = message.indexOf(" ", space + 1);//also check dat
result = message.substring(space,message.indexOf(' ', space + 1));
}
if(number == 1){
result = message.substring(0,message.indexOf(" "));
}
if(number>word){
lastWord = message.substring(message.lastIndexOf(" ")+1);
return lastWord;
}
else return result;
}
答案 0 :(得分:1)
目前的实施过于复杂,难以理解。
考虑这种替代算法:
index = 0
,以跟踪您在输入字符串中的位置start
像这样:
public static String pick(String message, int n) {
int index = 0;
for (int i = 1; i < n; i++) {
while (index < message.length() && message.charAt(index) != ' ') index++;
while (index < message.length() && message.charAt(index) == ' ') index++;
}
int start = index;
while (index < message.length() && message.charAt(index) != ' ') index++;
return message.substring(start, index);
}
请注意,如果n
高于输入中的字词,
这将返回空字符串。
(如果那不是你想要的,那么调整应该很容易。)
答案 1 :(得分:0)
CHEAT (使用正则表达式) 1
public static String pick(String message, int number){
Matcher m = Pattern.compile("^\\W*" + (number > 1 ? "(?:\\w+\\W+){" + (number - 1) + "}" : "") + "(\\w+)").matcher(message);
return (m.find() ? m.group(1) : null);
}
测试
System.out.println(pick("This is a test", 1));
System.out.println(pick("! This @ is # a $ test % ", 3));
System.out.println(pick("This is a test", 5));
输出
This
a
null
1)不允许StringTokenizer
和split
; - )
答案 2 :(得分:0)
这需要一些边缘案例处理(例如,少于n个单词),但这是我的想法。这与您的解决方案类似,但IMO不如janos&#39;。
public static String pick(String message, int n) {
int wordCount = 0;
String word = "";
int wordBegin = 0;
int wordEnd = message.indexOf(' ');
while (wordEnd >= 0 && wordCount < n) {
word = message.substring(wordBegin, wordEnd).trim();
message = message.substring(wordEnd).trim();
wordEnd = message.indexOf(' ');
wordCount++;
}
if (wordEnd == -1 && wordCount + 1 == n) {
return message;
}
if (wordCount + 1 < n) {
return "Not enough words to satisfy";
}
return word;
}
答案 3 :(得分:0)
Java中的大多数迭代现在可以被流替换。这是否是一种改进是一个(强烈的)意见的问题。
int thirdWordIndex = IntStream.range(0, message.size() - 1)
.filter(i -> Character.isWhiteSpace(message.charAt(i)))
.filter(i -> Character.isLetter(message.charAt(i + 1)))
.skip(2).findFirst()
.orElseThrow(IllegalArgumentException::new) + 1;