示例String str=“abcdefg”;int pos=3;写一个函数,对这个字符串进行如下处理:String result=“cbadgfe”。其中pos为字符串第3个元素d,将前后的字符串进行翻转,
abc->cba,efg->gfe后进行连接成cbadgfe,其中d保持不变,函数定义为:String result converse(String str,Int pos)
注意:翻转函数自己写,不要使用类库的函数;
------解决方案--------------------------------------------------------
简单乱写了一下, 应该能出效果
- Java code
public static String getString(String s){ String str = "" ; if(s!=null){ for (int i = 0; i < s.length(); i++) { int j = s.length() ; if(i==0){ str = str+s.substring(j) ; }else{ str = str+s.substring(j-i,j-i+1) ; } } str = str + s.substring(0, 1) ; } return str ; } public static void main(String[] args) throws Exception { String str = "abcdefg"; int pos = 3; String s = str.substring(0, pos) ; String s2 = str.substring( pos+1) ; System.out.println(getString(s) + str.substring(pos, pos+1) +getString(s2)); }
------解决方案--------------------------------------------------------
- Java code
public class TestFrame{ public static String reverseCell(String data){ StringBuffer sb = new StringBuffer(); for(int i=data.length()-1;i>=0;i--){ sb.append(data.charAt(i)); } return sb.toString(); } public static String reverseAll(String str,int pos){ if(str==null||str.length() == 0){ return str; } StringBuffer sb = new StringBuffer(); String temp = ""; for(int i = 0;i <(str.length()-1)/3 + 1;i++){ if(3*(i+1) < str.length()){ temp = reverseCell(str.substring(3*i, 3*(i+1))); } else{ temp = reverseCell(str.substring(3*i, str.length())); } sb.append(temp); } System.out.print(sb); return sb.toString(); } public static void main(String args[]){ String str="abcdefg";int pos = 3; reverseAll(str,pos); }}