Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I replace a space in a string with an underscore in C#?

Tags:

c#

I have strings such as:

var abc = "Menu Link"; 

Is there a simple way I can change the space to an underscore?

like image 443
Jessica Avatar asked Jan 25 '12 13:01

Jessica


People also ask

How do you replace a space underscore in a string?

Use the String. replaceAll method to replace all spaces with underscores in a JavaScript string, e.g. string. replaceAll(' ', '_') . The replaceAll method returns a new string with all whitespace characters replaced by underscores.

How do you replace a space in a string in C++?

Replacing space with a hyphen in C++ In this C++ program, the space in the string will be replaced with the hyphen. Firstly, the length of the string is determined by the length() function of the cstring class, then hyphen is filled into the space of the sentence by traversing the string as follows.

How do you replace all spaces in a string %20?

Approach: Count the total spaces in a string in one iteration, say the count is spaceCount. Calculate the new length of a string by newLength = length + 2*spaceCount; (we need two more places for each space since %20 has 3 characters, one character will occupy the blank space and for rest two we need extra space)


1 Answers

If you want to do it in place:

abc = abc.Replace(" ", "_"); 

Although do realize a new string instance will be created; it's not actually done in the same memory location - String is an immutable type.

like image 133
Yuck Avatar answered Sep 22 '22 18:09

Yuck