字符串之替换字符串中连续出现的指定字符串

题目:

字符串之替换字符串中连续出现的指定字符串

给定3个字符串str from to已知from字符串无重复字符,把str中所有from的子串全都替换成to字符串,连续出现from只需要换成一个to就可。

例如:

str="123adc" from = "adc" to ="4567" 返回1234567

str="123" from = "adc" to ="4567" 返回123

str="123adcabc" from = "adc" to ="X" 返回123X

 

实现代码:

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.chenyu.string.cn;
 
public class RaplaceString {
     
     public static void main(String[] args) {
         
         String target = "000abcabc123abc456abc789abcabc" ;
         String from = "abc" ;
         String to = "def" ;
         String result = replace(target, from ,to);
         System.out.print( "result:" + result);
         
     }
     
     
     public static String replace(String target, String from, String to) {
         
         if (target == null || "" .equals(target) || from == null || "" .equals(from) || to == null ) {
             return null ;
         }
         
         char [] targetChars = target.toCharArray();
         char [] fromChars = from.toCharArray();
         
         int count = 0 ;
         for ( int i = 0 ; i < targetChars.length; i++) {
             if (targetChars[i] == fromChars[count++]) {
                 if (count == from.length()) {
                     changeToZero(targetChars, count, i);
                     count = 0 ;
                 }
             } else {
                 count = 0 ;
             }
         }
         
         String res = "" ;
         
         for ( int i = 0 ; i < targetChars.length; i++) {
             if (targetChars[i] != 0 ) {
                 res = res + String.valueOf(targetChars[i]);
             }
             if (targetChars[i] == 0 && (i == 0 || targetChars[i- 1 ] != 0 )){
                 res = res + to;
             }连续出现的指定字符串
         }
         return res;
     }
     
     public static void changeToZero( char [] chars, int count, int end) {
         while (count-- != 0 ) {   //or while ((count--) > 0)
             chars[end--] = 0 ;    //如果char a = 0,就是把ASCII为0给a,如果char a = 'a',就是把ASCII为48给a
         }
     }
     
}

 

运行结果:

?
1
result:000def123def456def789def
以下仅供参考:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值