Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing spaces from string

I'm trying to remove all the spaces from a string derived from user input, but for some reason it isn't working for me. Here is my code.

public void onClick(View src) {     switch (src.getId()) {         case R.id.buttonGo:             String input = EditTextinput.getText().toString();             input = String.replace(" ", "");             url = ur + input + l;             Intent myIntent = new Intent(start.this, Main.class);             myIntent.putExtra("URL", url);             start.this.startActivity(myIntent);             break;         } } 
like image 761
Slicekick Avatar asked Aug 03 '11 19:08

Slicekick


People also ask

How do I remove spaces from a string?

The replaceAll() method of the String class replaces each substring of this string that matches the given regular expression with the given replacement. You can remove white spaces from a string by replacing " " with "".

How do I remove spaces between words in a string?

In Java, we can use regex \\s+ to match whitespace characters, and replaceAll("\\s+", " ") to replace them with a single space.

How do I remove spaces from a string in C++?

Remove spaces from std::string in C++ To remove this we will use the remove() function. With this remove() function it takes the beginning and end of the iterator, then takes the third argument that will be deleted from that iterator object.

How do you remove spaces in Python?

The strip() method is the most commonly accepted method to remove whitespaces in Python. It is a Python built-in function that trims a string by removing all leading and trailing whitespaces.


2 Answers

String  input = EditTextinput.getText().toString(); input = input.replace(" ", ""); 

Sometimes you would want to remove only the spaces at the beginning or end of the String (not the ones in the middle). If that's the case you can use trim:

input = input.trim(); 
like image 123
Cristian Avatar answered Oct 14 '22 10:10

Cristian


When I am reading numbers from contact book, then it doesn't worked I used

number=number.replaceAll("\\s+", ""); 

It worked and for url you may use

url=url.replaceAll(" ", "%20"); 
like image 32
Akhil Dad Avatar answered Oct 14 '22 09:10

Akhil Dad