在Java中,遇到非大写或标题案例的单词后截断字符串。

huangapple go评论73阅读模式
英文:

Truncate a string in Java after encountering a word that isn't uppercase or titlecase

问题

`我想从字符串中仅提取大写或标题大写的单词,并在遇到既非大写又非标题大写的单词后停止。

例如,DOCTOR Foo Bar is not here 将变为 DOCTOR Foo Bar,而 the NURSE Joy healed him 将返回一个空字符串,因为第一个单词既不是大写也不是标题大写。

我想要做类似于这样的事情,但是下面的代码不起作用。

String name = text.split(" ").stream()
                    .takeWhile(w -> w.isUpperCase() || w.isTitleCase())
                    .collect(joining(" "));

如您所愿,以下是代码部分的翻译:

String name = text.split(" ").stream()
                    .takeWhile(w -> w.isUpperCase() || w.isTitleCase())
                    .collect(joining(" "));
英文:

I want to take only the words in a string that are uppercase or titlecase, stopping after getting to a word that is neither.

For example, DOCTOR Foo Bar is not here would become DOCTOR Foo Bar and the NURSE Joy healed him would return an empty string since the first word is neither uppercase nor titlecase.

I'd like to do something similar to this, but the code below doesn't work.

String name = text.split(" ").stream()
                    .takeWhile(w -> w.isUpperCase() || w.isTitleCase())
                    .collect(joining(" "));

答案1

得分: 4

首先,您需要使用 Arrays.stream() 将数组转换为流,然后可以仅检查单词的第一个字母是否为大写,以满足您的条件。

String name = Arrays.stream(text.split(" "))
            .takeWhile(w -> Character.isUpperCase(w.charAt(0)))
            .collect(Collectors.joining(" "));
英文:

First, you need to use Arrays.stream() to turn array into stream and you can check only the first letter of the word is uppercase or not for your condition.

String name = Arrays.stream(text.split(" "))
        .takeWhile(w -> Character.isUpperCase(w.charAt(0)))
        .collect(Collectors.joining(" "));

答案2

得分: 2

你可以使用正则表达式 [A-Z][A-Za-z]* 来进行匹配,它表示第一个字母为大写,后面的字母可以是大写或小写,但是是可选的(因为有量词 *)。

示例:

import java.util.Arrays;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        String[] arr = { "DOCTOR Foo Bar is not here", "the NURSE Joy healed him", "He And I are pronouns" };

        for (String text : arr) {
            System.out.println(Arrays.stream(text.split("\\s+")).takeWhile(w -> w.matches("[A-Z][A-Za-z]*"))
                    .collect(Collectors.joining(" ")));
        }
    }
}

输出:

DOCTOR Foo Bar

He And I

请注意,我使用了 \s+ 作为分割标准,以匹配单词之间的一个或多个空格。

英文:

You can use matching criteria using the regex, [A-Z][A-Za-z]* which means the first letter as uppercase and the second onwards can be the upper or lower case but is optional (because of the quantifier, *).

Demo:

import java.util.Arrays;
import java.util.stream.Collectors;

public class Main {
	public static void main(String[] args) {
		String[] arr = { "DOCTOR Foo Bar is not here", "the NURSE Joy healed him", "He And I are pronouns" };

		for (String text : arr) {
			System.out.println(Arrays.stream(text.split("\\s+")).takeWhile(w -> w.matches("[A-Z][A-Za-z]*"))
					.collect(Collectors.joining(" ")));
		}
	}
}

Output:

DOCTOR Foo Bar

He And I

Note that I have used \s+ as the splitting criteria to match one or more whitespace between words.

答案3

得分: 0

似乎无法工作,因为它不是 Java 代码 在Java中,遇到非大写或标题案例的单词后截断字符串。 Java 中没有 String::isUpperCaseString::isTitleCase

无论如何,代码可能是这样的:

String name = Arrays.stream(text.split(" "))
                    .takeWhile(this::isUppercaseOrTitleCase)
                    .collect(joining(" "));

// 还需要编写附加函数
private boolean isUppercaseOrTitleCase(String string) {
    return string.equals(string.toUpperCase()) || Character.isUpperCase(string.charAt(0));
}
英文:

Seems like it cannot work because it's not a Java code 在Java中,遇到非大写或标题案例的单词后截断字符串。 There are no String::isUpperCase or String::isTitleCase in Java

Anyway it would be something like

String name = Arrays.stream(text.split(" "))
                    .takeWhile(this::isUppercaseOrTitleCase)
                    .collect(joining(" "));

// and you need to write additional function
private boolean isUppercaseOrTitleCase(String string) {
    return string.equals(string.toUpperCase()) || Character.isUpperCase(string.charAt(0));
}

答案4

得分: 0

以下是翻译好的代码部分:

我在Java方面更多地是初学者所以我选择了经典的尽管可能不是那么高效的方法用for循环来完成

这是我的代码

    String splitUpperCase(String input){
        String[] words = input.split(" ");
        String output = ""; 
        for (int i = 0; i < words.length; i++) {
            char[] ch = words[i].toCharArray();
            for (int ii = 0; ii < ch.length; ii++){
                if (Character.isUpperCase(ch[ii]) || Character.isTitleCase(ch[ii])){
                    output = output + words[i] + " ";
                    break;
                }
            }
        }
        return output;

输出结果为:

DOCTOR Foo Bar

<details>
<summary>英文:</summary>

I&#39;m more of a beginner in Java so I went with the classic, albeit maybe not that efficient approach of hammering it down in for loops

So this is what I got:

    String splitUpperCase(String input){
        String[] words = input.split(&quot; &quot;);
        String output = &quot;&quot;; 
        for (int i = 0; i &lt; words.length; i++) {
            char[] ch = words[i].toCharArray();
            for (int ii = 0; ii &lt; ch.length; ii++){
                if (Character.isUpperCase(ch[ii]) || Character.isTitleCase(ch[ii])){
                    output = output + words[i] + &quot; &quot;;
                    break;
                }
            }
        }
        return output;
   
And the output is:

    DOCTOR Foo Bar 

</details>



huangapple
  • 本文由 发表于 2020年10月23日 16:21:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/64496439.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定