Replace String

本文介绍了如何通过编程方法在给定字符串中区分大小写地替换字母'a'和'A'为'one'和'ONE'。通过使用正则表达式,实现了单个字符的替换而不影响其作为单词的一部分。示例代码演示了完整的解决方案。

Problem

From a given string, replace all instances of 'a' with 'one' and 'A' with 'ONE'.
Example Input: " A boy is playing in a garden"
Example Output: " ONE boy is playing in onegarden"
-- Not that 'A' and 'a' are to be replaced only when theyare single characters, not as part of another word.

Solution

 1 public static String replaceString(String s) {
 2     // s = s.replace("a ", "one ");
 3     // s = s.replace("A ", "ONE ");
 4 
 5 //        s = s.replaceAll("\\b(a)", "one");
 6 //        s = s.replaceAll("\\b(A)", "ONE");
 7 
 8     StringBuilder sb = new StringBuilder();
 9     for(String str : s.split(" ")) {
10         if(str.equals("a"))    sb.append("one ");
11         else if(str.equals("A")) sb.append("ONE ");
12         else sb.append(str + " ");
13     }
14     
15     return sb.toString();
16 }

 

转载于:https://www.cnblogs.com/superbo/p/4112113.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值