Reputation: 33
I would like to replace the string that contains breaklines and replace it with ".". However, in order to replace it, my method is to check how many breaklines it has and then perform replacing. This will make it add too many ".". Example
st = "I have something nice \n\n\n\n\n\n\n\n there"
String st = st.replace('\r', ' ').replace('\n\n\n', '.').replace('\n', '.').replace('\n\n', '.').replace('\n\n\n\n', '.');
My current way if I keep adding toooooo many replace then it will be: (Is there a smarter way to do so?)
I have something nice ........... there
My expected output:
I have something nice . there
Upvotes: 0
Views: 43
Reputation: 4633
This will help you:
st.replaceAll("(?:\\s*\n)+", ".");
\\s*\n
will escape all endlines which can be followed by spaces.
Also it will eliminate the space between the last char and the "." which is ponctuation rule.
Upvotes: 1
Reputation: 28269
Use String.replaceAll
with regex:
String st = "I have something nice \n\n\n\n\n\n\n\n there";
st = st.replaceAll("\n+", "."); // \n+ matches one or mutiple line breaks
System.out.println(st);//I have something nice . there
Upvotes: 1
Reputation: 3534
You can use a simple regex to replace all occurrences at one:
String st = "I have something nice \n\n\n\n\n\n\n\n there";
String replaceAll = st.replaceAll("\n+", ".");
Outputs:
I have something nice . there
Upvotes: 3