Adrija
Adrija

Reputation: 71

Replacing a character in a character array

I have the following program and I am trying to replace the space in the character array with "%20". For example, if I have this ['a','b',' '], the output would be this ['a','b','%20'].

This is the program:

import java.util.*;
import java.util.Scanner;
class some_str
{   String str1;

String space_method(String str)
{
    char[] chars = str.toCharArray();
    //char[] s3=new char[chars.length];
    for(char c:chars)
    //for (int i=0;i<chars.length;i++)
        if(Character.isWhitespace(c))
        {

            //over here I need to replace the space with '%20'
        }
    return "\n"+str;
      }

      }

public class space_str
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter string");
        String str= sc.nextLine();
        some_str st=new some_str();
        System.out.println(st.space_method(str));

    }

}

Please help, thanks.

Upvotes: 0

Views: 9663

Answers (3)

Shabaan Qureshi
Shabaan Qureshi

Reputation: 31

We know that Strings are immutable so to replace all the space characters with the %20 in our string, we can either first convert our String to the array of characters which is what you did and manipulate or we can use StringBuilder class, which you can think of as a mutable string but it is basically an array of chars internally. (There is also StringBuffer which essentially does the same thing as StringBuilder except it is thread safe).

Anyways, this following program does what you need to do.

public String spaceMethod(String str) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < str.length(); i++) {
        if (Character.isWhitespace(str.charAt(i))) {
            sb.append("%20");
        }
        else 
        {
        sb.append(str.charAt(i));
        }
    }
    return sb.toString();
}

Regarding the error in your code, the answer by Wow has already explained it. Good luck!

Upvotes: 1

Coder-Man
Coder-Man

Reputation: 2531

This is what you want:

String replaceSpace(String string) {
    StringBuilder sb = new StringBuilder();
    for(char c : string.toCharArray()) {
        if (c == ' ') {
            sb.append("%20");
        } else {
            sb.append(c);
        }
    }
    return sb.toString();
}

Note that you can't put "%20" into a char, because it is 3 symbols, not 1. That's why you shouldn't use arrays for this purpose.

With library functions you can use either string.replace(" ", "%20") or string.replaceAll(" ", "%20").

Upvotes: 1

Azhy
Azhy

Reputation: 706

Try this:-

str.replace(" ", "%20");

This method replace all spaces with %20 substring and not char because %20 is not a char.

Upvotes: 1

Related Questions