Java 当单词的第一个字母为大写时从字符串中删除单词

Java 当单词的第一个字母为大写时从字符串中删除单词,java,Java,我想从带大写字母的字符串中删除带大写字母的单词,但我不知道该怎么做 Original String: "bob Likes Cats" New String: "bob" 您可以尝试以下操作: String original = "bob Likes Cats"; String[] words = original.split(" "); //String of the final word. String finalword = ""; for(String word : words){

我想从带大写字母的字符串中删除带大写字母的单词,但我不知道该怎么做

Original String: "bob Likes Cats"
New String: "bob"

您可以尝试以下操作:

String original = "bob Likes Cats";
String[] words = original.split(" ");

//String of the final word.
String finalword = "";

for(String word : words){
    if(Character.isUpperCase(word.charAt(0)){
        //Word has a capital letter
    }else {
        //Add the word.
        finalword += word + " ";
    }
}
finalword
现在是一个带有小写字母的
字符串

请注意,
finalword
结尾可能包含额外的空格。
要删除末尾的空格,请执行以下操作:

finalword = finalword.substring(0,finalword.length()-1);

由于句子/字符串中的单词似乎由空格分隔,因此您的算法可能类似于:

  • 将空格上的字符串拆分为单词
  • 检查每个单词,并保存其中没有大写字符的单词
  • 创建一个新字符串,将所有保存的单词粘在一起,用空格分隔
  • 您还没有指定正在使用的编程语言,因此我将以PHP为例提供一种

    <?php
    
    // Your input string.
    $input = 'bob Likes Cats';
    
    /*
        1. preg_split() the input on one or more consecutive whitespace characters.
        2. array_filter() walks over every element returned by preg_split. The callback determines whether to filter the element or not.
        3. array_filter()'s callback tests every word for an uppercase ([A-Z]) character.
    */
    $filtered = array_filter(
        preg_split('/[\s]+/', $input),
        function ($word)
        {
            // preg_match() returns 1 if a match was made.
            return (preg_match('/[A-Z]/', $word) !== 1);
        }
    );
    
    // Glue back together the unfiltered words.
    $output = implode(' ', $filtered);
    
    // Outputs: bob
    echo $output;
    

    您尝试过什么?您的问题是什么?可能有很多方法可以做到这一点。。。您可以将原始字符串拆分为单词数组,然后通过省略包含大写字母的单词来重建字符串…顺便说一下,您的问题被否决,因为您没有表现出任何努力。。。
    
    <?php
    
    // Your input string.
    $input = 'bob Likes Cats';
    
    /*
        1. preg_split() the input on one or more consecutive whitespace characters.
        2. array_filter() walks over every element returned by preg_split. The callback determines whether to filter the element or not.
        3. array_filter()'s callback tests every word for an uppercase ([A-Z]) character.
    */
    $filtered = array_filter(
        preg_split('/[\s]+/', $input),
        function ($word)
        {
            // preg_match() returns 1 if a match was made.
            return (preg_match('/[A-Z]/', $word) !== 1);
        }
    );
    
    // Glue back together the unfiltered words.
    $output = implode(' ', $filtered);
    
    // Outputs: bob
    echo $output;