首页 > 试题广场 > 实现一个按字节来截取字符串的子串的方法,功能类似于Strin
[问答题]
实现一个按字节来截取字符串的子串的方法,功能类似于String类的substring()方法, String类是按字符截取的,例如”中国abc", substring(1,3), 将返回"国a"。这里要求按字节截取,一个英文字符当一个字节,一个中文字符当两个字节。

5个回答

添加回答
//以下仅供参考
  public void substring(String str, int toCount){
        int reInt = 0;
        String reStr = "";
        char[] tempChar = str.toCharArray();
        for (int kk = 0; (kk < tempChar.length && toCount > reInt); kk++){        
            String s1 = str.valueOf(tempChar[kk]);
            byte[] b = s1.getBytes();
            reInt += b.length;    //汉字的length为2
            reStr += tempChar[kk];
        }
        System.out.println(reStr);


发表于 2018-11-08 19:48:22 回复(0)
更多回答
public class InterceptString {
    public static void main(String args[]) {
        InterceptString is = new InterceptString();
        String str = "少一些功利主义的追求,多一些不为什么的坚持!" ;
        System.out.println(is.stringCut(str,0,10));
        
    }
    public String stringCut(String str,int start,int end) {
        byte[] strByte = str.getBytes();
        byte[] newstrByte = new byte[end - start];
        System.arraycopy(strByte, start, newstrByte, 0, end - start);
        String cutStr = new String(newstrByte);
        return cutStr;
    }
}

发表于 2019-04-02 20:58:18 回复(0)

public class Demo01 {
 public static void main(String[] args) {   System.out.println(Demo01.StringCut("中国你好abcdef", 0, 7));  }    public static String StringCut(String str,int from,int to){   byte[] a = str.getBytes();   byte[] b = new byte[to-from];   //将a数组里从索引为from的元素开始,   //复制到数组b里的索引为0的位置, 复制的元素个数为to-from个.   System.arraycopy(a, from, b, 0, to-from);   String newStr = new String(b);   return newStr;  } }
输入结果:中国你?


发表于 2018-12-03 15:57:57 回复(0)

public class CalendarB {

    

    public static String  cut(String c ,int b, int a){
        byte[]  s  =c.getBytes();
        byte[] s1 = new byte[a-b];
             
        System.arraycopy(s, b, s1, 0, a-b);
        String s2 = new String(s1);
        return s2;
                }
    public static void main(String [] args){
      
        System.out.println(cut("改革春风吹满地,中国人民真争气",4,10));
      
        
    }
    }

发表于 2019-03-27 14:32:18 回复(0)
 public String mySubString(String inputString, int from, int to) throws UnsupportedEncodingException {
  // TODO Auto-generated method stub
  byte[] bytes = inputString.getBytes("UTF-8"); 
  
  int size = to;
  if(to > bytes.length)
  {
   size = bytes.length;
  }
  
  byte[] resultBytes = new byte[size - from];
  
  int j = 0;
  for (int i = from; i < size; i++) {
   resultBytes[j] = bytes[i];
   j++;
  }
  
  return new String(resultBytes, "UTF-8");
 }

发表于 2018-11-09 14:53:38 回复(0)

扫一扫,把题目装进口袋

牛客网,程序员必备求职神器

扫描二维码,进入QQ群

扫描二维码,关注牛客网公众号