首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 字串長度計算:自訂函數與內建方法

     編輯:Java 相關知識

字串長度獲取

簡單需求:輸入一字串,輸出其長度。Java 內建 String.length() 即可完成,但教學常要求自訂函數練習。

基本實作


import java.util.Scanner;

public class StringLengthDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("請輸入字串:");
        String input = sc.nextLine(); // 讀整行含空白
        System.out.println("長度:" + strLen(input));
    }

    // 自訂函數(教學示範)
    public static int strLen(String s) {
        return s.length(); // 直接委派內建方法
    }
}

進階:不使用 length() 手動計算


public static int manualLength(String s) {
    int count = 0;
    try {
        while (true) {
            s.charAt(count); // 觸發 IndexOutOfBoundsException 結束
            count++;
        }
    } catch (IndexOutOfBoundsException e) {
        return count;
    }
}

利用例外控制流程(不推薦生產環境,僅供理解原理)。

補充:字元 vs 代碼點

  • length() 回傳 char 代碼單元數(UTF-16)。
  • 含 Emoji 或補充字元時,實際字元數請用 codePointCount(0, s.length())。

String emoji = "😀"; // U+1F600
System.out.println(emoji.length());           // 2 (char 數)
System.out.println(emoji.codePointCount(0, emoji.length())); // 1 (真實字元數)

最佳實務

直接使用 s.length() 即可滿足 99% 場景;涉及國際化字元時改用 codePointCount。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved