java - Add text before every vowel
问题描述
Hello I'm trying to add the String OB before every vowel(A,E,I,O,U) in my text. I can assume that the text is made up of all capital letters, no spaces or punctuation. These are handled by other methods I was able to create.
This is what I have so far:
public static String obify(String s){
String text = s;
String[] capVowels = {"A", "E", "I", "O", "U"};
for (String vow : capVowels){
text = text.replace(vow, "OB" + vow);
}
return text;
}
but when I pass it a sting it prints two OB before the first vowel. Example input: HELLOWOLD , output: HOBOBELLOBOWOBOLD
Any help would be appreciated with an explanation.
解决方案
You can use a regular expression character class to replace all the vowels with "OB{vowel}" via String#replaceAll
. For example
final String test = s.replaceAll("[AEIOU]", "OB$0");
The $0
represents the matched string, ie the vowel.
The reason you're getting duplicate "OB" strings in the result is because of your for-loop. The problem is you add more vowels with each iteration, ie the "O" in "OB", so when you get up to your "O" iteration, it's replacing the ones you added.
推荐阅读
- php - 将绝对部分路由到codeigniter中的控制器
- javascript - div 扩展动画最大高度不起作用。高度始终为 0
- amazon-web-services - cassandra 如何对多区域设置中的区域故障做出反应
- c# - “索引超出范围”异常在 DataGridView SelectionChanged 事件中引发而 FormLoad
- ruby-on-rails - #<# 的未定义方法“路径名”
我更新了项目的 Ruby 和 Rails 版本。
红宝石
2.2.3
->2.5.1
导轨
4.1.8
->5.1.7
现在,当我启动服务器时,出现此错误:
F, [2020-02-03T11:15:49.912
- arrays - RISC-V 循环遍历单词数组
- linux - 什么软件包在 RHEL8 中提供 systemd-networkd?
- vb.net - DateTime.Parse:无法提供值:找不到主机值
- visual-studio-2010 - RDLC 报告:页面顶部出现大的空白区域
- python - Python Unittest - 如果输入错误的键,MySQL 会挂起?