首页 > 解决方案 > 当单词的第一个字母大写时从字符串中删除单词

问题描述

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

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

标签: java

解决方案


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

  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;

推荐阅读