字符串截取

来源:互联网 发布:ubuntu设置ip自动获取 编辑:程序博客网 时间:2024/06/01 09:30

题目描述:

在java中,字符串“abcd”与字符串“ab你好”的长度是一样,都是四个字符。

但对应的字节数不同,一个汉字占两个字节。
定义一个方法,按照指定的字节数来取子串。

如:对于“ab你好”,如果取三个字节,那么子串就是ab与“你”字的半个,那么半个就要舍弃。如果取四个字节就是“ab你”,取五个字节还是“ab你”。


此题需要考虑的是编译器的编码格式,一般都是GBK、UTF-8这两种的

<span style="font-size:14px;">package cn.hncu.io.stringCut;import java.io.IOException;import java.util.Scanner;public class StringCutting2 {/** * @param args */public static void main(String[] args) {Scanner input=new Scanner(System.in);String str=input.next();try {byte []buf=str.getBytes();for (int i=0;i<=buf.length;i++){String res = cutString(str,i);System.out.println(i+":"+res);}} catch (IOException e) {e.printStackTrace();}}private static String cutString(String str, int len) throws IOException{if (System.getProperty("file.encoding").equalsIgnoreCase("gbk")){//获取系统编码格式return cutStringGbk(str, len);}if (System.getProperty("file.encoding").equalsIgnoreCase("utf-8")){//</span><span style="font-family: Arial, Helvetica, sans-serif;"><span style="font-size:14px;">获取系统编码格式</span></span><span style="font-size:14px;">return cutStringUtf8(str, len);}throw new RuntimeException("不支持当前系统的编码");}private static String cutStringGbk(String str, int len) throws IOException {byte buf[]=str.getBytes("gbk");int count=0;for (int i=len-1;i>=0;i--){if (buf[i]<0){count++;}else {break;}}int num=count%2;return new String(buf,0,len-num,"gbk");}private static String cutStringUtf8(String str, int len) throws IOException{byte buf[]=str.getBytes("utf-8");int count=0;for (int i=len-1;i>=0;i--){if (buf[i]<0){count++;}else {break;}}int num=count%3;return new String(buf,0,len-num,"utf-8");}}</span>

假如编译器编码格式是除了GBK和UTF-8以外的,可以采用下面的方式:

package cn.hncu.io.stringCut;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;public class StringCutting {private static final int bytes=5;public static void main(String[] args) throws IOException {InputStream in=System.in;InputStreamReader isr=new InputStreamReader(in);BufferedReader br=new BufferedReader(isr);String str=null;String code=System.getProperty("file.encoding");while ((str=br.readLine())!=null){byte buf[]=str.getBytes(code);str=new String(buf,0,bytes);System.out.println(str);}}}


0 0