Question

I have to split it and put %20 in between of the digits

var code="247834"

to

2%204%207%208%203%204

looks simple but i am not able to convert it.
any answer in scala or java is appreciated.

Was it helpful?

Solution

In Scala,

code.mkString("%20")

OTHER TIPS

In whatever language, your general technique should be to split the string into an array and then join it with the string '%20'. In PHP this would be

$array = str_split( $code);
$result = join( '%20', $array);

In Javascript:

var code="247834";
var myArray = code.split();
var result = myArray.join( '%20');

In one statement:

var result = code.split().join('%20'); 
// or "247834".split().join('%20');

Java??:

char[] myArray = "247844".toCharArray();
char[] result = StringUtils.join( myArray, '%20');

(the latter may need minor changes e.g. a join method is in TextUtils for Android and swaps the parameter order)

In Javascript

var code = "247834";
var output = '';

for (var i = 0; i < code.length; ++i)
{
    output = output + code.charAt(i) + ((i < code.length - 1) ? '%20' : '');

}

alert(output);

http://jsfiddle.net/sNrU7/1/

Java solution

Starting from the end, you can insert a delimiter using string buffer. This is the easiest solution and may not be the fastest.

Output

2%204%207%208%203%204  
2-4-7-8-3-4

Code

import java.lang.StringBuffer;

public class Test {
    public static void main(String[] args) {
        String str = "247834";
        System.out.println(separate(str, "%20"));
        System.out.println(separate(str, "-"));
    }

    public static String separate(String str, String delim) {
        StringBuffer buff = new StringBuffer(str);

        for (int i = str.length(); i > 0 ; i--) {
            if (i < str.length()) {
                buff.insert(i, delim);
            }
        }

        return buff.toString();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top