我正在玩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);
}
}
Run Code Online (Sandbox Code Playgroud)
我构建了正则表达式"[^a-zA-z]+"
来分割单词,例如字符串abc..abc
或者abc432abc
应该分割为["abc", "abc"]
.但是,当我尝试字符串时432abc
,我得到的结果是["", "abc"]
- 第一个元素来自words[]
一个空字符串,但我期待它只是["abc"]
.我无法弄清楚为什么这个正则表达式给了我""
这个案例的第一个元素.
归档时间: |
|
查看次数: |
1728 次 |
最近记录: |