微型 练习

来源:互联网 发布:淘宝客 领券链接 api 编辑:程序博客网 时间:2024/04/27 23:16
/** * http://bbs.csdn.net/topics/390787801?page=1#post-397391690 * 给出一个任意字符串要求按照a^nb^n(n>=2)输出,n为字符重复次数, * 例如给一个字符串“aaabbbcc1234ddee”,输出为aaabbb,aabb,bbcc,ddee。 * @author GT * */public class AnBnTest {public static void main(String[] args) {String str = "aaabbbcc1234ddeeeeffffaaa";char[] chs = str.toCharArray();for(int i=0;i<chs.length-1;i++){if( chs[i] != chs[i+1] ){int low = i;int high = i+1;show(low,high,chs);}}}public static void show(int low,int high,char[] chs){if((low-1)>=0 && (high+1)<chs.length){if(chs[low-1] == chs[low] && chs[high+1] == chs[high]){System.out.println(String.valueOf(chs).substring(low-1, high+1+1));show(low-1,high+1,chs);}}}}

编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串,但要保证汉字不被截取半个,如“我ABC”,4,应该截取“我AB”,输入“我ABC汉DEF”,6,应该输出“我ABC”,而不是“我ABC+汉的半个”。

public static int show(String str,int targetLength) throws Exception {char[] chs = str.toCharArray();int countLen = 0;int charLen = 0;for (int i = 0; i < chs.length; i++) {charLen = i;int len = String.valueOf(chs[i]).getBytes("GBK").length;countLen += len;if (countLen == targetLength) {break;} else if (countLen > targetLength) {charLen = charLen - 1;break;}}return charLen;}









0 0