华为OJ——按字节截取字符串

来源:互联网 发布:minecraft优化差 编辑:程序博客网 时间:2024/06/04 18:44

题目描述

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

 

输入描述:

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

输出描述:

截取后的字符串

输入例子:
我ABC汉DEF6
输出例子:
我ABC
方法一:

import java.util.*;public class Main{public static void main(String[] args) {Scanner scan=new Scanner(System.in);String str=scan.nextLine();int count=scan.nextInt();byte[] bytes=str.getBytes();int n=count;for(int i=0;i<n;i++){//判断最后一个是不是汉字,如果是,不输出if(!(str.charAt(i)>=0 && str.charAt(i)<=127) && i==n-1){System.out.println();//如果汉字,记录为输出了2字节}else if(!(str.charAt(i)>=0 && str.charAt(i)<=127)){Character ch=str.charAt(i);System.out.print(ch);n--;}else{//不是汉字,也不是最后一个,直接输出Character ch=str.charAt(i);System.out.print(ch);}}}}
方法二:

import java.util.*;public class Main{    public static void main(String[] args){        Scanner input = new Scanner(System.in);        while(input.hasNext()){            String str = input.next();            int len = input.nextInt();            int count = 0;            char[] arr = str.toCharArray();            String res = "";            for(int i = 0;i < arr.length;i++){                if(arr[i]<='z'){                    count++;                }else{                    count += 2;                }                if(count>len){                    break;                }                res += arr[i];            }            System.out.println(res);        }    }}





0 0
原创粉丝点击