gpt4 book ai didi

java - UVa #494 - 正则表达式 [^a-zA-z]+ 使用 Java 分割单词

转载 作者:行者123 更新时间:2023-12-02 09:18:23 34 4
gpt4 key购买 nike

我正在玩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..abcabc432abc 应拆分为 ["abc", "abc"]。但是,当我尝试字符串 432abc 时,结果是 ["", "abc"] - 来自 words[] 的第一个元素> 只是一个空字符串,但我期望只有 ["abc"]。我不明白为什么这个正则表达式给我第一个元素作为本例的 ""

最佳答案

查看拆分引用页:split reference

Each element of separator defines a separate delimiter character. If two delimiters are adjacent, or a delimiter is found at the beginning or end of this instance, the corresponding array element contains Empty. The following table provides examples.

由于您有多个连续的分隔符,因此您将得到空数组元素

关于java - UVa #494 - 正则表达式 [^a-zA-z]+ 使用 Java 分割单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14079277/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com