Replace All Spaces in a String with '+'

Replace all spaces in a string with '+'

Here's an alternative that doesn't require regex:

var str = 'a b c';
var replaced = str.split(' ').join('+');

How to replace all spaces in a string

var result = replaceSpace.replace(/ /g, ";");

Here, / /g is a regex (regular expression). The flag g means global. It causes all matches to be replaced.

Replace all spaces in a string with +

Use strings.ReplaceAll

tw.Text = strings.ReplaceAll(tw.Text, " ", "+")

If you're using an older version of go (< 1.12), use strings.Replace with -1 as limit (infinite)

tw.Text = strings.Replace(tw.Text, " ", "+", -1)

Replace all plus signs (+) with space in a string

The + character has special significance in regular expressions. It's a quantifier meaning one or more of the previous character, character class, or group.

You need to escape the +, like this:

i.replace(new RegExp("\\+","g"),' ')...

Or more simply, by using a precompiled expression:

i.replace(/\+/g,' ')...

Write a method to replace all spaces in a string with '%20'

You are passing the length as 6, which is causing this. Pass length as 7 including space.
Other wise

for(i = length - 1; i >= 0; i--) {

will not consider last char.

How to replace spaces middle of string in Dart?

Using RegExp like

String result = _myText.replaceAll(RegExp(' +'), ' ');

Write a method to replace all spaces in a string with '%20'?

In this loop, the program adds %20 before each word:

   for(String w: words){
sentence.append("%20");
sentence.append(w);
}

That will produce incorrect results, for example for a b it will give %20a%20b.

There's a much simpler solution:

public String replace(String str) {
return str.replaceAll(" ", "%20");
}

Or, if you really don't want to use .replaceAll, then write like this:

public String replace(String str) {
String[] words = str.split(" ");
StringBuilder sentence = new StringBuilder(words[0]);

for (int i = 1; i < words.length; ++i) {
sentence.append("%20");
sentence.append(words[i]);
}

return sentence.toString();
}


Related Topics



Leave a reply



Submit