前言:
請編寫一個截取字符串的函數,輸入為一個字符串和字節數,輸出為按字節截取的字符串。但是要保證漢字不被截半個,如“我ABC”4,應該截為“我AB”,輸入“我ABC漢DEF”6,應該輸出“我ABC”,而不是“我ABC”+“漢”字的半個。
2、解析思想
本題容易產生困惑的是中文字符和英文字符如何處理,在這里需要考慮漢字和英文字符的占用字節數問題,中文字符占兩個字節,英文字符占一個字節,了解這個關鍵點后,那么編寫代碼就容易啦!
3、Java代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
import java.util.Scanner; public class Interception { static String ss; //要進行截取操作的字符串 static int n; //截取的字符串的字節數 public static void main(String[] args) { System.out.println( "請輸入字符串:" ); Scanner scStr = new Scanner(System.in); //從鍵盤獲取字符串 ss = scStr.next(); //將Scanner對象中的內容以字符串的形式取出來 System.out.println( "請輸入字節數:" ); Scanner scByte = new Scanner(System.in); //從鍵盤獲取字符串 n = scByte.nextInt(); //將Scanner對象中的內容以數值的形式取出來 Interception(setValue()); //方法與方法間的套用 } public static String[] setValue() { //此方法的作用是將字符串轉換成字符串數組 String[] string = new String[ss.length()]; //創建一個字符數組string for ( int i = 0 ; i < string.length; i++) { string[i] = ss.substring(i, i + 1 ); //將字符串ss中的第i個字符取出,放入字符數組中string中 } return string; //將這個字符數組返回 } public static void Interception(String[] string) { int count = 0 ; String m = "[\u4e00-\u9fa5]" ; //漢字的正則表達試 System.out.println( "每" + n + "字節進行劃分的字符串如下所示:" ); for ( int i = 0 ; i < string.length; i++) { if (string[i].matches(m)) { //將字符數組中的每一個元素與表則表達式進行匹配,如果相同則返回true count = count + 2 ; //如果當前字符是漢字,計數器count就加2 } else { count = count + 1 ; //如果當前字符不是漢字,計數器count就加1 } if (count < n) { //如果當前計數器count的值小于n,則輸出當前字符 System.out.print(string[i]); } else if (count == n) { //如果當前計數器count的值等于n,則輸出當前字符 System.out.print(string[i]); count = 0 ; System.out.println(); //內循環結果,則需要換行,起到控制打印格式的作用 } else { count = 0 ; //如果當前計數器count的值大于n,則計數器count清零,接著執行外部循環 System.out.println(); } } } } |
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:http://blog.csdn.net/qq_35246620/article/details/53455639