-1

I have a string in Java which could look like this:

我今天說了:Good morning 的一句英語

I want it to become this:

我 今 天 說 了 :Good morning 的 一 句 英 語

Basically a space is added between every Chinese characters or symbols while other languages are unaffected.

I think determining the Unicode block for CJK characters could be a good way to do it, as Japanese and Korean are not expected to be used.

There are many questions on adding a space to every character, regardless of language, which does not achieve my aim.

Fei Kuan
  • 27
  • 5
  • 6
    `There are many questions on adding a space to every character, regardless of language, which does not achieve my aim.` Why not? What have you tried and what went wrong with your attempt? – tnw May 02 '17 at 15:53
  • 1
    Possible duplicate of [Add spaces between the characters of a string in Java?](http://stackoverflow.com/questions/7189293/add-spaces-between-the-characters-of-a-string-in-java) – Nikolas Charalambidis May 02 '17 at 16:00
  • 1
    I have tried solutions similar to what Nikolas suggested as possible duplicate, which adds spaces to every single character blindly. I want a space to be added between every Chinese(or CJK) characters only, while leaving English/Latin characters untouched. – Fei Kuan May 02 '17 at 16:36
  • 1
    @FeiKuan Have you Googled `java determine if character is chinese`? Use virtually any of the resources immediately available from that search and pair it with the solution you found already to add spaces between all characters. – tnw May 02 '17 at 16:55
  • http://stackoverflow.com/questions/26357938/detect-chinese-character-in-java (dont forget to upvote) – petey May 02 '17 at 17:03

1 Answers1

2

You can use a RegExp and the replaceAll method of the String class:

public static void main(String[] args) {
  String test = "我今天說了:Good morning 的一句英語";

  System.out.println(test.replaceAll("(?<=\\p{sc=Han})", " "));
}

Cheers, A.