java 實(shí)現(xiàn)截取字符串并按字節(jié)分別輸出實(shí)例代碼
前言:
請(qǐng)編寫(xiě)一個(gè)截取字符串的函數(shù),輸入為一個(gè)字符串和字節(jié)數(shù),輸出為按字節(jié)截取的字符串。但是要保證漢字不被截半個(gè),如“我ABC”4,應(yīng)該截為“我AB”,輸入“我ABC漢DEF”6,應(yīng)該輸出“我ABC”,而不是“我ABC”+“漢”字的半個(gè)。
2、解析思想
本題容易產(chǎn)生困惑的是中文字符和英文字符如何處理,在這里需要考慮漢字和英文字符的占用字節(jié)數(shù)問(wèn)題,中文字符占兩個(gè)字節(jié),英文字符占一個(gè)字節(jié),了解這個(gè)關(guān)鍵點(diǎn)后,那么編寫(xiě)代碼就容易啦!
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; //要進(jìn)行截取操作的字符串 static int n; //截取的字符串的字節(jié)數(shù) public static void main(String[] args) { System.out.println( "請(qǐng)輸入字符串:" ); Scanner scStr = new Scanner(System.in); //從鍵盤(pán)獲取字符串 ss = scStr.next(); //將Scanner對(duì)象中的內(nèi)容以字符串的形式取出來(lái) System.out.println( "請(qǐng)輸入字節(jié)數(shù):" ); Scanner scByte = new Scanner(System.in); //從鍵盤(pán)獲取字符串 n = scByte.nextInt(); //將Scanner對(duì)象中的內(nèi)容以數(shù)值的形式取出來(lái) Interception(setValue()); //方法與方法間的套用 } public static String[] setValue() { //此方法的作用是將字符串轉(zhuǎn)換成字符串?dāng)?shù)組 String[] string = new String[ss.length()]; //創(chuàng)建一個(gè)字符數(shù)組string for ( int i = 0 ; i < string.length; i++) { string[i] = ss.substring(i, i + 1 ); //將字符串ss中的第i個(gè)字符取出,放入字符數(shù)組中string中 } return string; //將這個(gè)字符數(shù)組返回 } public static void Interception(String[] string) { int count = 0 ; String m = "[\u4e00-\u9fa5]" ; //漢字的正則表達(dá)試 System.out.println( "每" + n + "字節(jié)進(jìn)行劃分的字符串如下所示:" ); for ( int i = 0 ; i < string.length; i++) { if (string[i].matches(m)) { //將字符數(shù)組中的每一個(gè)元素與表則表達(dá)式進(jìn)行匹配,如果相同則返回true count = count + 2 ; //如果當(dāng)前字符是漢字,計(jì)數(shù)器count就加2 } else { count = count + 1 ; //如果當(dāng)前字符不是漢字,計(jì)數(shù)器count就加1 } if (count < n) { //如果當(dāng)前計(jì)數(shù)器count的值小于n,則輸出當(dāng)前字符 System.out.print(string[i]); } else if (count == n) { //如果當(dāng)前計(jì)數(shù)器count的值等于n,則輸出當(dāng)前字符 System.out.print(string[i]); count = 0 ; System.out.println(); //內(nèi)循環(huán)結(jié)果,則需要換行,起到控制打印格式的作用 } else { count = 0 ; //如果當(dāng)前計(jì)數(shù)器count的值大于n,則計(jì)數(shù)器count清零,接著執(zhí)行外部循環(huán) System.out.println(); } } } } |
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
原文鏈接:http://blog.csdn.net/qq_35246620/article/details/53455639