Java,按标点符号拆分字符串,处理字符串,将标点符号添加回字符串



我有这样的字符串:

Some text, with punctuation sign!

我用标点符号拆分它,使用 str.split("regex") .然后,我在拆分后处理接收到的数组中的每个元素(切换字符)。

我想将所有标点符号添加回它们的位置。所以结果应该是这样的:

Smoe txet, wtih pinctuatuon sgin!
最好的

方法是什么?

在一小行中完成整个事情怎么样?

str = str.replaceAll("(?<=\b\w)(.)(.)", "$2$1");

一些测试代码:

String str = "Some text, with punctuation sign!";
System.out.println(str.replaceAll("(?<=\b\w)(.)(.)", "$2$1"));

输出:

Smoe txet, wtih pnuctuation sgin!

由于您不添加或删除字符,因此不妨只使用String.toCharArray()

char[] cs = str.toCharArray();
for (int i = 0; i < cs.length; ) {
  while (i < cs.length() && !Character.isLetter(cs[i])) ++i;
  int start = i;
  while (i < cs.length() && Character.isLetter(cs[i])) ++i;
  process(cs, start, i);
}
String result = new String(cs);

其中process(char[], int startInclusive, int endExclusive)是一种在索引之间混淆数组中的字母的方法。

我会逐个字符地通读字符串。

  • 如果字符是标点符号,请将其附加到字符串生成器

  • 如果字符不是标点符号,请继续读取字符,直到到达标点字符,然后处理该单词并将其追加到 StringBuilder 中。然后跳到下一个标点符号字符。

这会打印,而不是附加到 StringBuilder,但你得到的想法:

String sentence = "This is a test, message!";
for (int i = 0; i<sentence.length(); i++) {
  if (Character.isLetter(sentence.charAt(i))) {
    String tmp = "" +sentence.charAt(i);
    while (Character.isLetter(sentence.charAt(i+1)) && i<sentence.length()) {
      i++;
      tmp += sentence.charAt(i);
    }
    System.out.print(switchChars(tmp));
  } else {
    System.out.print(sentence.charAt(i));
  }
}
System.out.println();

您可以使用:

String[] parts = str.split(","); 
// processing parts
String str2 = String.join(",", parts); 

最新更新