按字节截取字符串

描述 知识点 运行时间限制 内存限制 输入 输出 样例输入 样例输出

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

  • 接口说明

原型:public String cutString(String s, int length)

字符串
10M
128

输入待截取的字符串及长度

截取后的字符串

我ABC汉DEF 6
我ABC
package com.lw.test_3;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test {

	
	public static void main(String[] args) {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		String read=null;
		String split_s=null;
		int split;
		String result=null;
		
		try {
			read=br.readLine();
			split_s=br.readLine();
			split=Integer.parseInt(split_s);

			int count=0;
			int index=0;
			while(count<split){
				char c=read.charAt(index++);
				byte[] bytes=(c+"").getBytes();
				if(bytes.length>1){
					//判断为双字节字符
					count=count+2;
					if(count<=split){
						System.out.print(c);
					}
					
				}
				else {
					//单字节字符
					System.out.print(c);
					count++;
				}
				//防止数组越界
				if(index>=read.length())
					break;
			}		
			
		} catch (IOException e) {
			
			e.printStackTrace();
		}
	}

}

猜你喜欢

转载自hnulanwei.iteye.com/blog/2238306