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

Java实现:将含缩写词句子末尾的换行符替换为空格

Hey there! Let's work through how to fix this problem of replacing the newline character when your text contains specific abbreviations.

First, let's break down the issues in your original code:

  • Your loop starts at i=1, which skips the first abbreviation "dl" in your list. You should iterate over all items starting from i=0.
  • Using z.replaceFirst("\\n"," ") replaces the first newline in the entire string, not the one that comes after the abbreviation you found. Also, since Strings in Java are immutable, you need to assign the result back to z for changes to stick.

Here are two solid solutions to achieve your goal:


Solution 1: Use Regular Expressions (Clean & Efficient)

This approach lets you match any line containing your target abbreviations and replace the trailing newline with a space in one go. It's great for handling all instances across your text.

import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AbbreviationLineFix {
    public static void main(String[] args) {
        List<String> abbreviations = Arrays.asList("dl", "Dl", "Prf", "Ing");
        // Build a regex pattern to match any of the abbreviations
        String regexPattern = String.format("(.*(%s).*)\\n", String.join("|", abbreviations));
        Pattern pattern = Pattern.compile(regexPattern);

        // Example input text
        String text = "Report from dl. department\nRegular update here\nPrf. Miller submitted notes\n";
        
        Matcher matcher = pattern.matcher(text);
        // Replace matching line endings with a space
        String fixedText = matcher.replaceAll("$1 ");

        System.out.println(fixedText);
        // Output:
        // Report from dl. department 
        // Regular update here
        // Prf. Miller submitted notes 
    }
}

How this works:

  • String.join("|", abbreviations) creates a regex like dl|Dl|Prf|Ing to match any of your target abbreviations.
  • The full regex (.*(%s).*)\\n captures the entire line containing an abbreviation, then replaces the trailing \n with a space using the first capture group ($1).

Solution 2: Manual Index Manipulation (More Control)

If you prefer working directly with string indices, use a StringBuilder (since it's mutable) to find each abbreviation and replace the next newline after it.

import java.util.Arrays;
import java.util.List;

public class AbbreviationIndexFix {
    public static void main(String[] args) {
        List<String> abbreviations = Arrays.asList("dl", "Dl", "Prf", "Ing");
        String text = "dl. status update\nAnother line\nIng. approval received\n";
        StringBuilder sb = new StringBuilder(text);

        for (String abbr : abbreviations) {
            int abbrPosition;
            // Find all occurrences of the abbreviation
            while ((abbrPosition = sb.indexOf(abbr)) != -1) {
                // Look for the first newline AFTER the abbreviation
                int newlinePosition = sb.indexOf("\n", abbrPosition + abbr.length());
                if (newlinePosition != -1) {
                    // Replace the newline with a space
                    sb.setCharAt(newlinePosition, ' ');
                }
            }
        }

        String fixedText = sb.toString();
        System.out.println(fixedText);
    }
}

How this works:

  • We use StringBuilder to modify the text in place (avoids creating multiple String objects).
  • For each abbreviation, we loop through all its occurrences, then find the first newline that comes after it. When found, we replace that newline character with a space.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:10:11