Java实现字符串中的连续数字的反转

来源:互联网 发布:linux 中文时间格式 编辑:程序博客网 时间:2024/05/21 02:43

示例:"1abc123abc123"  处理之后为  "1abc321abc321"


思路:1、将字符串转化为数组

            2、 依次找出一个连续数字串的头尾下标

            3、找到一组头尾下标后就执行一次swap(char[] ch, int start, int end),这个函数的作用是使数组ch,

                  索引start~end的范围内元素反转。

            4、这样执行一次后,继续找下一组,直到结束


public class 把字符串中的数字反转 {/* *对于给定数组,将索引start到end范围内的元素反转,实现很简单。 */public static void swap(char[] arr, int start, int end){char temp ;while (start < end){temp       =  arr[start];arr[start] =  arr[end];arr[end]   =  temp;start++;end--;}}    /* *String转化为数组,for循环依次一组连续数字一组连续数字的找,找到一次交换一次。 */public static String fun(String string){char[] ch = string.toCharArray();int start = 0;int end = 0;         boolean flag = true;for (int i=0; i<ch.length; i++){if (ch[i]<='9' && ch[i]>='0'){if (flag){ start = i; flag = false;}//@1if (!flag){ if(i == ch.length-1) swap(ch,start,i);}//@3}else{                  if (!flag){ end = i-1; flag = true; swap(ch,start,end);}//@2}}return new String(ch);}public static void main(String[] args) {System.out.println(把字符串中的数字反转.fun("1abc123abc123"));}}

这里主要讲解一下fun(string)函数,一组数字头尾的求法,及@3处的特例:

   其中的顺序:start→end→swap(ch,start,end),这里用flag作为求start和end的同步信号,初始为true,先求start。

   @1:遇到第一个数字,把 i 值保存到start,flag置false,这样i++后start的值才不会改变。

   @2:连续数字走完后,遇到第一个非数字,把 i-1 保存到end,这样一组求出,执行swap(),

             然后及时flag置true,求下一组。

   @3:上面给的例子末尾为连续数字,最后一组,就是当start赋值后,找不到下一个非数字,也就不能赋值end。

             @3就是应付这种情况的。

                         

 


0 0