实战:字符串处理

本课是Phase 2的综合实战,通过5个项目巩固字符串处理能力。

项目1:字符串反转

综合运用:StringBuilder、String.toCharArray()。

需求

编写方法反转字符串。

实现

JAVA
public class StringReverse {
    // 方法1:StringBuilder
    public static String reverse1(String str) {
        if (str == null) return null;
        return new StringBuilder(str).reverse().toString();
    }
    
    // 方法2:字符数组
    public static String reverse2(String str) {
        if (str == null) return null;
        char[] chars = str.toCharArray();
        int left = 0, right = chars.length - 1;
        while (left < right) {
            char temp = chars[left];
            chars[left] = chars[right];
            chars[right] = temp;
            left++;
            right--;
        }
        return new String(chars);
    }
    
    // 方法3:递归
    public static String reverse3(String str) {
        if (str == null || str.length() <= 1) {
            return str;
        }
        return reverse3(str.substring(1)) + str.charAt(0);
    }
    
    public static void main(String[] args) {
        String s = "Hello, World!";
        System.out.println("原字符串:" + s);
        System.out.println("反转1:" + reverse1(s));
        System.out.println("反转2:" + reverse2(s));
        System.out.println("反转3:" + reverse3(s));
    }
}

输出:

TEXT
原字符串:Hello, World!
反转1:!dlroW ,olleH
反转2:!dlroW ,olleH
反转3:!dlroW ,olleH

项目2:单词计数

综合运用:String.split()、for-each循环。

需求

统计字符串中的单词数量。

实现

JAVA
public class WordCount {
    public static int countWords(String str) {
        if (str == null || str.trim().isEmpty()) {
            return 0;
        }
        // 按空格分割,trim去除首尾空格
        String[] words = str.trim().split("\\s+");
        return words.length;
    }
    
    public static void main(String[] args) {
        System.out.println(countWords("Hello World"));           // 2
        System.out.println(countWords("  Hello   World  "));     // 2
        System.out.println(countWords("Java is awesome"));       // 3
        System.out.println(countWords(""));                      // 0
        System.out.println(countWords(null));                    // 0
    }
}

项目3:回文判断

综合运用:StringBuilder、双指针。

需求

判断字符串是否是回文(正读反读都一样)。

实现

JAVA
public class Palindrome {
    // 方法1:StringBuilder反转
    public static boolean isPalindrome1(String str) {
        if (str == null) return false;
        String reversed = new StringBuilder(str).reverse().toString();
        return str.equals(reversed);
    }
    
    // 方法2:双指针
    public static boolean isPalindrome2(String str) {
        if (str == null) return false;
        int left = 0, right = str.length() - 1;
        while (left < right) {
            if (str.charAt(left) != str.charAt(right)) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
    
    // 忽略大小写和非字母数字
    public static boolean isPalindromeIgnore(String str) {
        if (str == null) return false;
        String cleaned = str.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
        return isPalindrome2(cleaned);
    }
    
    public static void main(String[] args) {
        System.out.println(isPalindrome1("racecar"));        // true
        System.out.println(isPalindrome1("hello"));          // false
        System.out.println(isPalindromeIgnore("A man, a plan, a canal: Panama"));  // true
    }
}

项目4:日期计算

综合运用:LocalDate、ChronoUnit、Period。

需求

计算两个日期之间的天数差、年月日差。

实现

JAVA
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;

public class DateCalculator {
    // 计算天数差
    public static long daysBetween(LocalDate start, LocalDate end) {
        return ChronoUnit.DAYS.between(start, end);
    }
    
    // 计算年月日差
    public static Period periodBetween(LocalDate start, LocalDate end) {
        return Period.between(start, end);
    }
    
    // 判断闰年
    public static boolean isLeapYear(int year) {
        return LocalDate.of(year, 1, 1).isLeapYear();
    }
    
    // 获取某月天数
    public static int daysInMonth(int year, int month) {
        return LocalDate.of(year, month, 1).lengthOfMonth();
    }
    
    public static void main(String[] args) {
        LocalDate start = LocalDate.of(2026, 1, 1);
        LocalDate end = LocalDate.of(2026, 12, 31);
        
        System.out.println("天数差:" + daysBetween(start, end));  // 364
        
        Period period = periodBetween(start, end);
        System.out.println("年月日差:" + period);  // P11M30D
        
        System.out.println("2026是闰年:" + isLeapYear(2026));  // false
        System.out.println("2024是闰年:" + isLeapYear(2024));  // true
        System.out.println("2026年2月天数:" + daysInMonth(2026, 2));  // 28
    }
}

项目5:字符串加密

综合运用:charAt()、StringBuilder、ASCII码运算。

需求

实现简单的凯撒加密(每个字母后移3位)。

实现

JAVA
public class CaesarCipher {
    public static String encrypt(String text, int shift) {
        StringBuilder result = new StringBuilder();
        
        for (char c : text.toCharArray()) {
            if (Character.isLetter(c)) {
                char base = Character.isUpperCase(c) ? 'A' : 'a';
                // 加密:(字符 - 基准 + 偏移) % 26 + 基准
                char encrypted = (char) ((c - base + shift) % 26 + base);
                result.append(encrypted);
            } else {
                result.append(c);
            }
        }
        
        return result.toString();
    }
    
    public static String decrypt(String text, int shift) {
        return encrypt(text, 26 - shift);
    }
    
    public static void main(String[] args) {
        String original = "Hello, World!";
        int shift = 3;
        
        String encrypted = encrypt(original, shift);
        String decrypted = decrypt(encrypted, shift);
        
        System.out.println("原文:" + original);
        System.out.println("加密:" + encrypted);    // Khoor, Zruog!
        System.out.println("解密:" + decrypted);    // Hello, World!
    }
}

综合练习

练习1:统计字符频率

JAVA
import java.util.HashMap;
import java.util.Map;

public class CharFrequency {
    public static Map<Character, Integer> frequency(String str) {
        Map<Character, Integer> map = new HashMap<>();
        for (char c : str.toCharArray()) {
            map.put(c, map.getOrDefault(c, 0) + 1);
        }
        return map;
    }
    
    public static void main(String[] args) {
        String s = "hello world";
        Map<Character, Integer> freq = frequency(s);
        
        for (Map.Entry<Character, Integer> entry : freq.entrySet()) {
            System.out.println("'" + entry.getKey() + "' : " + entry.getValue());
        }
    }
}

练习2:驼峰命名转换

JAVA
public class CamelCase {
    // 下划线转驼峰
    public static String toCamelCase(String str) {
        StringBuilder result = new StringBuilder();
        boolean capitalizeNext = false;
        
        for (char c : str.toCharArray()) {
            if (c == '_') {
                capitalizeNext = true;
            } else {
                if (capitalizeNext) {
                    result.append(Character.toUpperCase(c));
                    capitalizeNext = false;
                } else {
                    result.append(c);
                }
            }
        }
        
        return result.toString();
    }
    
    // 驼峰转下划线
    public static String toSnakeCase(String str) {
        StringBuilder result = new StringBuilder();
        
        for (char c : str.toCharArray()) {
            if (Character.isUpperCase(c)) {
                result.append('_');
                result.append(Character.toLowerCase(c));
            } else {
                result.append(c);
            }
        }
        
        return result.toString();
    }
    
    public static void main(String[] args) {
        System.out.println(toCamelCase("hello_world"));  // helloWorld
        System.out.println(toSnakeCase("helloWorld"));   // hello_world
    }
}

❓ 常见问题

Q 字符串操作效率低怎么办?
A 大量拼接用StringBuilder,频繁查找用正则表达式。
Q 如何处理null和空字符串?
A 方法开头检查null和空串,返回合理的默认值或抛出异常。
Q 正则表达式怎么学?
A 先掌握基础语法(. * + ? [] ()),再逐步学习高级用法。

📖 小节

📝 作业

  1. 字符串压缩: 将"aaabbbcc"压缩为"a3b3c2"
  2. 邮箱验证: 判断字符串是否是合法的邮箱格式
  3. 日期工具类: 编写DateUtils工具类,包含计算年龄、天数差、格式化等方法

下一课

下一课我们将进入Phase 3,学习 类与对象,进入面向对象编程的世界。

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏