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

    xiaoxiao2021-12-14  18

    题目:

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

    给定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 以下仅供参考: 转载于: 字符串之替换字符串中 连续出现的指定字符串
    转载请注明原文地址: https://ju.6miu.com/read-968101.html

    最新回复(0)