ITeye博客

截取字符串

abc778201 · 2011-03-01 20:41 · 编程语言 · Markdown

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

import java.util.Scanner; public class InterceptionStr{ static String ss; ////要进行截取操作的字符串 static int n; ////截取的字符串的字节数 public static void main(String args){ System.out.println("请输入字符串"); Scanner scStr=new Scanner(System.in); ss=scStr.next(); System.out.println("请输入字节数"); Scanner scByte=new Scanner(System.in); n=scByte.nextInt(); Interception(setValue()); ///方法与方法中的套用 }

public static String setValue(){
    String string=new String;
    for(int i=0;i<string.length;i++){
      string*=ss.substring(i,i+1);
    }
    return string;
}

public static void Interception(String string){
    int count=0;
    String m="";   ////汉字的正则表达式
    System.out.println("以每"+n+"字节划分的字符串如下所示:");
    for(int i=0;i<string.length;i++){
       if(string*.matches(m)){
           count=count+2;
       }else{
           count=count+1;
       }
       if(count<n){
            System.out.print(string*);
       }else if(count==n){
            System.out.print(string*);
            count=0;
            System.out.println(); 
       }else{
            count=0;
            System.out.println();
       }

    }

}

}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。