当单词的首字母大写时从字符串中删除单词

时间:2018-11-17 19:11:43

标签: java

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

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

3 个答案:

答案 0 :(得分:0)

您可以尝试以下操作:

String original = "bob Likes Cats";
String[] words = original.split(" ");
ArrayList<String> newstring = new ArrayList<>();

for(String word : words){
    if(Character.isUpperCase(word.charAt(0)){
    //Word has a capital letter
    }else {
        //add the word.
        newstring.add(word);
    }
}

//Get a String of the final word.
String finalword = "";
for(String word: newstring){
    finalword +=word;
}

finalword是带有小写字母的单词。

答案 1 :(得分:0)

看到句子/字符串中的单词似乎被空格隔开,您的算法可能类似于:

  1. 将空格上的字符串分割成单词。
  2. 遍历每个单词,并保存其中没有大写字母的单词。
  3. 创建一个新字符串,将所有保存的单词粘合在一起,并用空格隔开。

您尚未指定要使用的编程语言,因此我将以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;

答案 2 :(得分:-1)

public static String removeCapitalFirstLetterWords(String str) {
    StringBuilder buf = new StringBuilder();

    for (String word : str.split("\\W+")) {
        if (Character.isUpperCase(word.charAt(0)))
            continue;
        if (buf.length() > 0)
            buf.append(' ');
        buf.append(word);
    }

    return buf.toString();
}