【发布时间】:2012-12-29 06:25:35
【问题描述】:
我在玩UVa #494,我设法用下面的代码解决了它:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Main {
public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line;
while((line = in.readLine()) != null){
String words[] = line.split("[^a-zA-z]+");
int cnt = words.length;
// for some reason it is counting two words for 234234ddfdfd and words[0] is empty
if(cnt != 0 && words[0].isEmpty()) cnt--; // ugly fix, if has words and the first is empty, reduce one word
System.out.println(cnt);
}
System.exit(0);
}
}
我构建了正则表达式"[^a-zA-z]+" 来拆分单词,例如字符串abc..abc 或abc432abc 应该拆分为["abc", "abc"]。但是,当我尝试使用字符串432abc 时,结果是["", "abc"] - words[] 的第一个元素只是一个空字符串,但我希望只有["abc"]。我不明白为什么这个正则表达式给了我第一个元素 "" 在这种情况下。
【问题讨论】: