黑马程序员技术交流社区

标题: 截取字符交流 [打印本页]

作者: faith    时间: 2014-4-14 13:59
标题: 截取字符交流
package javaTest;

public class zifujiequ {
        public static String getStr(int n, String str){
                return str.substring(0,n);
               
        }
        public static void main(String[]args){
                String a = "中国abc";
                System.out.println(a.substring(1, 3));
               
        }

}
截取第二位和第三位字符  和大家分享下 大家还有其他方法吗?
作者: 向日葵的曙光    时间: 2014-4-14 22:36
这是我的方法 仅供参考
方法一:
public class CutString{

        public static void main(String[] args) throws Exception {
               
                System.out.println(SubStringByByte("abc你好", 5));
        }
       
        public static String SubStringByByte(String str,int index)
        {
               
                if(index >= str.getBytes().length)
                {
                        return str;
                }
               
                String temp = str;
                for(int i = 0;i<str.length();i++)
                {
                        if(temp.getBytes().length <= index)
                        {
                                break;
                        }
                        temp = temp.substring(0, temp.length() - 1);
                }
                return temp;
        }
}
方法二:
package com.cg.test5;

import java.io.IOException;
public class Test {
        public static void main(String[] args) throws IOException {
                String string="abc你好呀,我真的很想进黑马!Hello";
                int len=string.getBytes("utf-8").length;
                for(int x=0;x<len;x++){
                        System.out.println("截取"+(x+1)+"个字节结果是:"+cutStringByU8Byte(string,x+1));
                }
        }
       
        public static String cutStringByU8Byte(String str,int len) throws IOException{
                byte [] buf=str.getBytes("utf-8");
                int count=0;
                for(int x=len-1;x>=0;x--){
                        if(buf[x]<0)
                                count++;
                        else {
                                break;
                        }
                }
                if(count%3==0)
                        return new String(buf,0,len,"utf-8");
                else if(count%3==1)
                        return new String(buf,0,len-1,"utf-8");
                else {
                        return new String(buf,0,len-2,"utf-8");
                }
        }
       
}

作者: jsjchenlong    时间: 2014-4-15 00:21
瞻仰一下。
作者: faith    时间: 2014-4-15 08:33
向日葵的曙光 发表于 2014-4-14 22:36
这是我的方法 仅供参考
方法一:
public class CutString{

厉害  我到现在没有完整的思路




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2