擷取字串以多行的形式輸出
問題描述:輸入一個字串(包括漢字和英文字母以及其他符號)以及每行的位元組數。輸出為一個字串被分割為多行輸出。
舉例:
Please input string:
dasa大大dad
Please input string number per line:
4
Print the string as 4 byte per line:
dasa
大大
dad
這裡需要注意的是:中文字元佔兩個位元組,英文字元佔一個位元組。漢字不能輸出半個(也就是說實際一行輸出的位元組等於或比要求少一個)。
java程式碼實現如下:
package test1;
import java.util.Scanner;
public class InterceptionStr
{
static String ss;//用於記錄輸入的字串
static int n; //用於記錄每行輸出的位元組數
public static void main(String[] args)
{
System.out.println("Please input string:");//提示使用者輸入要擷取的字串
Scanner inStr = new Scanner(System.in);
ss = inStr.next();//將使用者輸入以字串的形式取出
System.out.println("Please input string number per line:");//提示使用者輸入每行的位元組數
Scanner inByte = new Scanner(System.in);
n = inByte.nextInt();//以整數的形式取出使用者輸入
interception(setValue());//呼叫函式完成格式化輸出
}
//將使用者的輸入轉換成字串陣列便於處理
public static String[] setValue()
{
String[] string = new String[ss.length()];
for (int i = 0; i < string.length; i++)
{
string[i] = ss.substring(i, i + 1);// 左閉右開
}
return string;
}
public static void interception(String[] string)
{
int count = 0;
String m = "[\u4e00-\u9fa5]";//漢字的正規表示式
System.out.println("Print the string as " + n +" byte per line:");
for (int i = 0; i < string.length; i++)
{
if (string[i].matches(m))
count += 2;//漢字佔兩個位元組
else
count += 1;//其他字元佔一個位元組
if (count < n)
System.out.print(string[i]);
else if (count == n)
{
System.out.print(string[i]);
count = 0;
System.out.println();
}
else
{
count = 0;
System.out.println();
}
}
}
}
相關文章
- C語言中以字串形式輸出列舉變數C語言字串變數
- PHP字串擷取PHP字串
- php字串擷取函式,支援中文擷取PHP字串函式
- MySQL 字串函式:字串擷取MySql字串函式
- php中英字串擷取PHP字串
- shell 擷取變數的字串變數字串
- jQuery 擷取字串以省略號替代jQuery字串
- jQuery字串擷取詳解jQuery字串
- iOS擷取NSString字串iOS字串
- Mysql字串擷取函式MySql字串函式
- js字串以鍵盤打字方式輸出:JS字串
- Shell中的字串擷取介紹字串
- 統計字串中數字個數,並將數字字串形式輸出字串
- iOS NSString字串擷取方法iOS字串
- Linux下的字串擷取詳解Linux字串
- javascript擷取指定指定區間的字串JavaScript字串
- iOS擷取特定的字串(正則匹配)iOS字串
- Linux shell指令碼的字串擷取Linux指令碼字串
- Go 語言在命令列以表格的形式輸出結構體切片Go命令列結構體
- Oracle以逗號分隔的字串拆分為多行資料Oracle字串
- Spring Boot Filter中擷取響應輸出內容Spring BootFilter
- JavaScript 擷取指定指定區間字串JavaScript字串
- php 擷取中英文混合字串PHP字串
- C#常用字串擷取C#字串
- shell 使用陣列及字串擷取陣列字串
- 字串擷取 slice,substr,substring 的區別字串
- Swift 4.0 字串擷取,拼接,字串富文字顯示Swift字串
- awk多行日誌排序輸出排序
- MVC接收以post形式傳輸的各種引數MVC
- swift 字串學習 (index用法和擷取)Swift字串Index
- php 如何擷取中文字串PHP字串
- css實現的字串擷取程式碼例項CSS字串
- 對url字串中域名的三種擷取方式字串
- 包含中文的字串中擷取前N個字元字串字元
- ***PHP各種編碼的漢字字串擷取PHP字串
- android 幾個經常用到的字串的擷取Android字串
- 檔案路徑類 字串的各種擷取方式,包括擷取到檔名字串
- ncurses輸出函式:字元+字串的輸出函式字元字串