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

多条件下从Java String提取指定字符:修改现有代码实现需求

Solution for Extracting Characters from Title Strings

Let's break down how to implement your requirement: we need to handle two cases for each title—single-word titles get their first two characters, multi-word titles get the first character of each word. Here's the modified Java code with explanations:

public class TitleProcessor {
    public static final String[] titles = new String[]{"Raj", "Niraj Kumar"};

    public static void main(String[] args) {
        for (int i = 0; i < titles.length; i++) {
            String title = titles[i];
            // Split title into words (handles multiple spaces with \\s+)
            String[] words = title.split("\\s+");
            String extracted;

            if (words.length > 1) {
                // For multi-word titles: collect first character of each non-empty word
                StringBuilder sb = new StringBuilder();
                for (String word : words) {
                    if (!word.isEmpty()) {
                        sb.append(word.charAt(0));
                    }
                }
                extracted = sb.toString();
            } else {
                // For single-word titles: take first two chars (handle short words safely)
                String singleWord = words[0];
                extracted = singleWord.length() >= 2 ? singleWord.substring(0, 2) : singleWord;
            }

            // Output or store the result as needed
            System.out.println("Original: " + title + " | Extracted: " + extracted);
        }
    }
}

Key Details:

  • Robust Word Splitting: Using split("\\s+") instead of just " " ensures we handle edge cases like multiple spaces between words or accidental leading/trailing spaces.
  • Efficient Multi-Word Processing: A StringBuilder is used to build the result quickly, and we skip empty strings that might come from split operations.
  • Safe Single-Word Handling: We check if the word has at least two characters before taking the substring—this prevents IndexOutOfBoundsException for short single-word titles like "Al" or "A".

Test Output:

When you run this code, you'll get exactly the expected results:

Original: Raj | Extracted: Ra
Original: Niraj Kumar | Extracted: NK

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:40:25