0

I'm Dealing with a string that contain 6 spaces after each other :

Example

String h = "abc      def";

How I can remove Only 5 spaces

I tried String.replace(h.substring(i,i+1),"")

and also used string Builder

not working

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140

1 Answers1

4

You can replace 6 spaces with 1 space using below line:

jshell> String a = "abc      def";
a ==> "abc      def"

jshell> a = a.replaceAll("     ", "");
a ==> "abc def"

Also, as shared in the comments, if you want to replace any number of spaces with one space, you can use regex as shared below:

jshell> String a = "abc      def";
a ==> "abc      def"

jshell> a = a.replaceAll("\\s+", " ");
a ==> "abc def"

jshell> String a = "abc            def";
a ==> "abc            def"

jshell> a = a.replaceAll("\\s+", " ");
a ==> "abc def"
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
Aman Chhabra
  • 3,824
  • 1
  • 23
  • 39