java - 当单词的第一个字母大写时从字符串中删除单词
问题描述
我想从带有大写字母的字符串中删除带有大写字母的单词,但我不知道该怎么做?
Original String: "bob Likes Cats"
New String: "bob"
解决方案
看到您的句子/字符串中的单词似乎用空格分隔,您的算法可能类似于:
- 将空格上的字符串拆分为单词。
- 检查每个单词,并保存其中没有大写字符的单词。
- 创建一个新字符串,将所有保存的单词粘合在一起,用空格分隔。
您还没有指定您使用的编程语言,所以我将提供一种 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;
推荐阅读
- python - pandas rank 函数 2 列的高值和低值
- ubuntu - Nginx 安装后未启动 [emerg] open() "/etc/nginx/nginx.conf" failed (2: No such file
- python - 在自定义函数参数中将列表的值设为布尔值
- dns - Cloudflare,故意在其他端口上暴露 ip
- python - 有条件地应用 jinja2 过滤器
- intellij-idea - 无法识别 intelij 黄瓜项目中特征文件的步骤定义
- php - 为循环的每个项目添加不同的类以构建砌体布局
- c++ - 带有 std::map 的基于 C++ 范围的 for() 循环
- sql - 带有 <> 的 strftime() 没有给出正确的结果
- java - OpenCsv CsvToBeanBuilder 不构建 bean