1. 程式人生 > >典型字串處理程式碼

典型字串處理程式碼

package com.arithmetic;

public class StringApi {

    // 判斷字串是否是一條迴文
    public static boolean isPalindrome(String s) {
        int N = s.length();
        for (int i = 0; i < N/2; i++) {
            if (s.charAt(i) != s.charAt(N-1-i)) {
                return false;
            }
        }
        return true;
    }

    // 提取檔名和副檔名
    public static void getFileName(String fileName) {
        int dot = fileName.indexOf(".");
        String baseName = fileName.substring(0,dot);
        String extendName = fileName.substring(dot + 1, fileName.length());
        System.out.println("檔名:" + baseName);
        System.out.println("副檔名:" + extendName);
    }

    // 檢查一個字串陣列的元素是否按照字母表元素排序
    public static boolean isSorted(String[] a) {
        for (int i = 1; i < a.length; i++) {
           if (a[i-1].compareTo(a[i]) > 0) {
               return false;
           }
        }
        return true;
    }

    public static void main(String[] args) {
        String a = "ABCDDCBA";
        System.out.println(isPalindrome(a));

        String fileName = "軟體迴文測試系統文件.docx";
        getFileName(fileName);

        String[] arr = {"ab","abce","abc","ddd"};

        boolean sorted = isSorted(arr);
        System.out.println(sorted);

    }


}