Mohamed Lee
Mohamed Lee

Reputation: 29

Remove a single space character from a long string of spaces

I am trying to remove a single space character from a long string of let's say 10 spaces. Example (first row is before, second row is after, dots used instead of single spaces for better understanding):

".........."
"........."

Just one space removal at a time.

Upvotes: 0

Views: 123

Answers (4)

MikeFHay
MikeFHay

Reputation: 9023

Use String.replaceFirst

s = s.replaceFirst(" ", "");

Upvotes: 1

MadProgrammer
MadProgrammer

Reputation: 347314

If you really don't are about where the space is removed from (assuming the text is all the same), simply drop the first character, for example...

String spaces = "          ";
spaces = spaces.substring(1);

Upvotes: 0

Óscar López
Óscar López

Reputation: 236044

You can use a StringBuilder for easily removing a character from a string:

String input = "123345";
String output = new StringBuilder(input).deleteCharAt(2).toString();
System.out.println(output);
=> "12345"

Upvotes: 1

Cedric Simon
Cedric Simon

Reputation: 4659

If you want to remove the fist space of a String you could use this code:

public class Test {
    public static void main(String[] args) {
       String a ="123 654 877    98798";
       System.out.println(a);
       System.out.println(a.substring(0,a.indexOf(" "))+a.substring(a.indexOf(" ")+1));
    }
}

Upvotes: 1

Related Questions