9

In my application i want to replace space with %20 in my string.I tried in this way,

String flag1="http://74.208.194.142/admin/upload_image/1342594079_images (2).jpg";
flag1.replaceAll("", "%20");

But it is not working please help me.I am getting null pointer exception.

keyser
  • 18,829
  • 16
  • 59
  • 101
user1083266
  • 1,751
  • 3
  • 24
  • 26

4 Answers4

10

You should do it like:

flag1 = flag1.replaceAll(" ", "%20");

first you were putting empty string instead of space.. and second you must return the value into the flag1 variable..

Nermeen
  • 15,883
  • 5
  • 59
  • 72
5

Have a look at http://docs.oracle.com/javase/1.5.0/docs/api/java/net/URLEncoder.html

It is not only the blanks that need to be replaced. URLs consist of special caracters for special meanings (e.g. the question mark to start the query string)

String flag1 = URLEncoder.encode("This string has spaces", "UTF-8")
thobens
  • 1,729
  • 1
  • 15
  • 34
4

In flag1.replaceAll(), your space is missing. try:

String flag1="http://74.208.194.142/admin/upload_image/1342594079_images (2).jpg";
flag1 = flag1.replaceAll(" ", "%20");

and set the result to the flag1.

stealthjong
  • 10,858
  • 13
  • 45
  • 84
4
    String flag1="http://74.208.194.142/admin/upload_image/1342594079_images (2).jpg";
    URI uri = null;
    try {
        uri = new URI(flag1.replaceAll(" ", "%20"));
    } catch (URISyntaxException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println(uri);

The console will display output as

http://74.208.194.142/admin/upload_image/1342594079_images%20(2).jpg

Ram kiran Pachigolla
  • 20,897
  • 15
  • 57
  • 78