を気にすべてのシンボルを含む正規表現であるような
String[] array = new String[] { "this", "is", "a", "test", "." };
String joined = String.join(" ", array);
joined = joined.replaceAll(" ([.,])", "$1");
何か、:また、あなたは本当にループまたはStringBuildersを必要としませんあなたは次の配列があればあなたは句読点を見つけ、最後の空白を避けることができる表現は、例えば、:だから
{"this", "is", "a", "test", ".", "and", "this", "is", "another",
"test", ";", "here", "is", "one", "test", "more", "!"};
を、あなたがこの方法で実装できます
private static String regex = "[.!;?\\-]";
String[] str = {"this", "is", "a", "test", ".", "and", "this", "is",
"another", "test", ";", "here", "is", "one", "test", "more", "!"};
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length; i++) {
if (str[i].matches(regex)) {
sb.deleteCharAt(sb.length() - 1);
}
sb.append(str[i] + " ");
}
System.out.println(sb.toString());
出力:
String[] str = {"this", "is", "a", "test", "."};
String test = Arrays.stream(str).reduce(new String(), (p,q) -> p+" "+q).replace(" .", ".");
System.out.println("out ::" + test);
出力:
this is a test. and this is another test; here is one test more!
もっと一般的なルールが必要だと思います。あなたはどんな厳しい状況の下でスペースを必要としませんか?次の配列要素が厳密に ''。 – ruakh
最後の文字のような一般的な条件が必要であると仮定します。 –
はい。いくつかの句読点。 – user697911