Java機試題目_怎樣截取字串

來源:互聯網
上載者:User

標籤:

面試題怎樣截取字串

考題題幹

編寫一個截取字串的函數,輸入為一個字串和位元組數,輸出為按位元組截取的字串。但是要保證漢字不被截半個,如"ABC"4,應該截為"AB",輸入"ABCDEF"6,應該輸出"ABC",而不是"ABC+漢的半個"

試題分析

本面試題容易產生困惑的是中文字元和英文字元,在這裡需要考慮漢字和英文字元的佔用位元組數問題,中文字元佔兩個位元組,英文字元佔一個位元組,理解了這個,就很容易完成本題了。

 

代碼

    package t0806;      import java.util.Scanner;      public class test3 {          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(); } } } }

 

Java機試題目_怎樣截取字串

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.