You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现字符串首字母及句号后首字母大写?

Capitalize First Letter and Letters After Periods in Java

Hey there! Let's solve this string formatting problem you're working on—turning the first letter of the entire string uppercase, plus the first letter right after every period. Here are two practical approaches in Java that get the job done:

Approach 1: Use Regular Expressions (Clean & Concise)

Regex is perfect for this kind of pattern-based replacement. We'll target two specific scenarios:

  • The very first lowercase letter in the string
  • Any lowercase letter that comes after a period followed by one or more spaces

Here's the code to implement this:

public class StringCapitalizer {
    public static void main(String[] args) {
        String text = "hello. i am Gabriele. i am 21 years old!";
        
        // Regex pattern to find positions needing capitalization
        String regex = "(^[a-z])|(\\.\\s+[a-z])";
        StringBuilder resultBuilder = new StringBuilder();
        java.util.regex.Matcher matcher = java.util.regex.Pattern.compile(regex).matcher(text);
        
        while (matcher.find()) {
            // Handle the two matching cases separately
            if (matcher.group(1) != null) {
                // Capitalize the first character of the entire string
                matcher.appendReplacement(resultBuilder, matcher.group(1).toUpperCase());
            } else {
                // Keep the period and spaces, only capitalize the following letter
                String match = matcher.group(2);
                resultBuilder.append(match.substring(0, match.length() - 1))
                          .append(Character.toUpperCase(match.charAt(match.length() - 1)));
            }
        }
        matcher.appendTail(resultBuilder);
        
        System.out.println(resultBuilder.toString());
        // Output: Hello. I am Gabriele. I am 21 years old!
    }
}

Approach 2: Manual Character Traversal (More Transparent)

If you want full visibility into how each character is processed, manually looping through the character array is a great choice. Here's the step-by-step logic:

  1. Capitalize the first character immediately
  2. Loop through the rest of the characters—whenever you hit a period, skip any following spaces and capitalize the next non-space character

Check out the code:

public class StringCapitalizer {
    public static void main(String[] args) {
        String text = "hello. i am Gabriele. i am 21 years old!";
        if (text.isEmpty()) {
            System.out.println(text);
            return;
        }
        
        char[] charArray = text.toCharArray();
        // Capitalize the first character of the string
        charArray[0] = Character.toUpperCase(charArray[0]);
        
        // Traverse to handle letters after periods
        for (int i = 1; i < charArray.length; i++) {
            if (charArray[i] == '.' && i + 1 < charArray.length) {
                // Skip all spaces immediately after the period
                int nextLetterIndex = i + 1;
                while (nextLetterIndex < charArray.length && Character.isWhitespace(charArray[nextLetterIndex])) {
                    nextLetterIndex++;
                }
                // Capitalize the next valid character if it exists
                if (nextLetterIndex < charArray.length) {
                    charArray[nextLetterIndex] = Character.toUpperCase(charArray[nextLetterIndex]);
                }
            }
        }
        
        String result = new String(charArray);
        System.out.println(result);
        // Output: Hello. I am Gabriele. I am 21 years old!
    }
}

Quick Notes

  • The regex method is shorter and great for quick implementations, but you need to be comfortable with pattern matching.
  • The manual traversal method is more verbose, but it makes it easier to adjust for edge cases (like multiple spaces after a period or empty input strings).

内容的提问来源于stack exchange,提问作者CastoldiG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 17:47:40