用标点符号修改Java字符串中单词的字符,但保留标点符号的位置吗?

时间:2019-04-15 03:09:13

标签: java string

例如,考虑以下String的列表,而不考虑逗号的反引号:

"Hello"
"Hello!"
"I'm saying Hello!"
"I haven't said hello yet, but I will."

现在让我们说我想对每个 word 的字符执行某些操作-例如,说我想反转字符, but 保持标点符号的位置。因此结果将是:

"olleH"
"olleH!"
"m'I gniyas olleH!"
"I tneva'h dias olleh tey, tub I lliw."

理想情况下,我希望我的代码独立于对字符串执行的操作(另一个示例是对字母进行随机混排),并且独立于所有标点符号(例如,连字符,撇号,逗号,句号,英文破折号等。所有在执行该操作后仍保持其原始位置。这可能需要某种形式的正则表达式。

为此,我想我应该将所有标点符号的索引和字符保存在给定单词中,执行该操作,然后将所有标点符号重新插入其正确位置。但是,我想不出一种方法或要使用的类。

我第一次尝试,但是不幸的是,这不适用于标点符号,这是关键:

jshell> String str = "I haven't said hello yet, but I will."
str ==> "I haven't said hello yet, but I will."

jshell> Arrays.stream(str.split("\\s+")).map(x -> (new StringBuilder(x)).reverse().toString()).reduce((x, y) -> x + " " + y).get()
$2 ==> "I t'nevah dias olleh ,tey tub I .lliw"

有人知道我该如何解决吗?非常感谢。不需要完整的工作代码-可能只是我可以用来执行此操作的适当类的路标。

2 个答案:

答案 0 :(得分:4)

无需为此使用正则表达式,并且您当然不应该使用split("\\s+"),因为这样会丢失连续的空格以及空白字符的类型,即结果的空格可能不正确。 / p>

您也不应该使用charAt()或类似的名称,因为那样的话将不支持Unicode补充平面中的字母,即,以Java字符串形式存储的Unicode字符作为代理对。

基本逻辑:

  • 找到单词的开头,即字符串或空白后的第一个字符的开头。
  • 找到单词的末尾,即空格前的最后一个字符或字符串的末尾。
  • 从头到尾并行迭代:
    • 跳过不是字母的字符。
    • 交换字母。

作为Java代码,具有完全的Unicode支持:

public static String reverseLettersOfWords(String input) {
    int[] codePoints = input.codePoints().toArray();
    for (int i = 0, start = 0; i <= codePoints.length; i++) {
        if (i == codePoints.length || Character.isWhitespace(codePoints[i])) {
            for (int end = i - 1; ; start++, end--) {
                while (start < end && ! Character.isLetter(codePoints[start]))
                    start++;
                while (start < end && ! Character.isLetter(codePoints[end]))
                    end--;
                if (start >= end)
                    break;
                int tmp = codePoints[start];
                codePoints[start] = codePoints[end];
                codePoints[end] = tmp;
            }
            start = i + 1;
        }
    }
    return new String(codePoints, 0, codePoints.length);
}

测试

System.out.println(reverseLettersOfWords("Hello"));
System.out.println(reverseLettersOfWords("Hello!"));
System.out.println(reverseLettersOfWords("I'm saying Hello!"));
System.out.println(reverseLettersOfWords("I haven't said hello yet, but I will."));
System.out.println(reverseLettersOfWords("Works with surrogate pairs: + "));

输出

olleH
olleH!
m'I gniyas olleH!
I tneva'h dias olleh tey, tub I lliw.
skroW htiw etagorrus sriap: + 

请注意,末尾的特殊字母是here中“脚本(或书法)”,“粗体”列中显示的前4个字母,例如是Unicode Character 'MATHEMATICAL BOLD SCRIPT CAPITAL A' (U+1D4D0),在Java中是两个字符"\uD835\uDCD0"


更新

以上实现已优化为反转单词的字母。要应用任意操作来修饰单词的字母,请使用以下实现:

public static String mangleLettersOfWords(String input) {
    int[] codePoints = input.codePoints().toArray();
    for (int i = 0, start = 0; i <= codePoints.length; i++) {
        if (i == codePoints.length || Character.isWhitespace(codePoints[i])) {
            int wordCodePointLen = 0;
            for (int j = start; j < i; j++)
                if (Character.isLetter(codePoints[j]))
                    wordCodePointLen++;
            if (wordCodePointLen != 0) {
                int[] wordCodePoints = new int[wordCodePointLen];
                for (int j = start, k = 0; j < i; j++)
                    if (Character.isLetter(codePoints[j]))
                        wordCodePoints[k++] = codePoints[j];
                int[] mangledCodePoints = mangleWord(wordCodePoints.clone());
                if (mangledCodePoints.length != wordCodePointLen)
                    throw new IllegalStateException("Mangled word is wrong length: '" + new String(wordCodePoints, 0, wordCodePoints.length) + "' (" + wordCodePointLen + " code points)" +
                                                                " vs mangled '" + new String(mangledCodePoints, 0, mangledCodePoints.length) + "' (" + mangledCodePoints.length + " code points)");
                for (int j = start, k = 0; j < i; j++)
                    if (Character.isLetter(codePoints[j]))
                        codePoints[j] = mangledCodePoints[k++];
            }
            start = i + 1;
        }
    }
    return new String(codePoints, 0, codePoints.length);
}
private static int[] mangleWord(int[] codePoints) {
    return mangleWord(new String(codePoints, 0, codePoints.length)).codePoints().toArray();
}
private static CharSequence mangleWord(String word) {
    return new StringBuilder(word).reverse();
}

如果需要,您当然可以用对传入的mangleWordFunction<int[], int[]>参数的调用来替换对Function<String, ? extends CharSequence>方法的硬编码调用。

mangleWord方法实现的结果与原始实现相同,但是您现在可以轻松实现不同的处理算法。

例如要随机化字母,只需shuffle codePoints数组:

private static int[] mangleWord(int[] codePoints) {
    Random rnd = new Random();
    for (int i = codePoints.length - 1; i > 0; i--) {
        int j = rnd.nextInt(i + 1);
        int tmp = codePoints[j];
        codePoints[j] = codePoints[i];
        codePoints[i] = tmp;
    }
    return codePoints;
}

示例输出

Hlelo
Hlleo!
m'I nsayig oHlel!
I athen'v siad eohll yte, btu I illw.
srWok twih rueoatrsg rpasi: +

答案 1 :(得分:1)

我怀疑有一个更有效的解决方案,但这是一个幼稚的解决方案:

  1. 将句子拆分为空格上的单词(注意-如果您有多个空格,我的实现会出现问题)
  2. 带标点符号
  3. 颠倒每个单词
  4. 仔细阅读每个字母,并在反义词中插入字符,并在必要时在原始词中插入标点符号
public class Reverser {

    public String reverseSentence(String sentence) {
        String[] words = sentence.split(" ");
        return Arrays.stream(words).map(this::reverseWord).collect(Collectors.joining(" "));
    }

    private String reverseWord(String word) {
        String noPunctuation = word.replaceAll("\\W", "");
        String reversed = new StringBuilder(noPunctuation).reverse().toString();
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < word.length(); ++i) {
            char ch = word.charAt(i);
            if (!Character.isAlphabetic(ch) && !Character.isDigit(ch)) {
                result.append(ch);
            }
            if (i < reversed.length()) {
                result.append(reversed.charAt(i));
            }
        }
        return result.toString();
    }
}