zoukankan      html  css  js  c++  java
  • 按字节截取字符串

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

     i=2,3,4,5,6,7,8,9,10
     n=1,2,2,3,3,4,4,5,6    

    View Code
     1 public class ByteTest
    2 {
    3 public static void main(String[] args)
    4 {
    5 String s="我ABC汉DEF";
    6 System.out.println(SubString(s,5));
    7 }
    8 public static String SubString(String str,int len)
    9 {
    10 byte[] b=null;
    11 try
    12 {
    13 b=str.getBytes("Unicode");
    14 }
    15 catch(Exception ex)
    16 {
    17 ex.printStackTrace();
    18 }
    19 int i=2;
    20 int n=0;
    21 for(;i<b.length&&n<len;i++)
    22 {
    23 if(i%2==1)
    24 {
    25 n++;
    26 }
    27 else
    28 {
    29 if(b[i]!=0)
    30 {
    31 n++;
    32 }
    33 }
    34 }
    35 if(i%2==1)
    36 {
    37 if(b[i-1]!=0)
    38 {
    39 i--;
    40 }
    41 else
    42 {
    43 i++;
    44 }
    45 }
    46 String temp=null;
    47 try
    48 {
    49 temp=new String(b,0,i,"Unicode");
    50 }
    51 catch(Exception ex)
    52 {
    53 ex.printStackTrace();
    54 }
    55 return temp;
    56 }
    57 }



  • 相关阅读:
    邻接矩阵
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
  • 原文地址:https://www.cnblogs.com/xiongyu/p/2269101.html
Copyright © 2011-2022 走看看