I want to replace any space between in word in with dash in C#
. But my problem is when I want remove space in sample string like this:
"a b"
or
"a b"
When I try this, I get this result:
"a--b"
and "a---b"
How can I put one dash for any count of space between the word?
Like this:
"ab"
"ab"
you can use like below
string xyz = "1 2 3 4 5";
xyz = string.Join( "-", xyz.Split( new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries ));
Reference
You can simply use Regex.Replace
here.
Regex.Replace("a b", @"\s+", "-");
\\s looks for a space
and + counts for spaces, if one or more spaces found sequentially. The pattern will be matched and replaced.
This can be done with many approaches. using Regular Expressions:
string a = "a b c de";
string b = Regex.Replace(a, "\\s+", "-");
Or if you dont want to use Regex, Here's a function which will take a string and the character to replace as arguments and return the formatted string.
public string ReplaceWhitespaceWithChar(string input,char ch)
{
string temp = string.Empty;
for (int i = 0; i < input.Length; i++)
{
if (input[i] != ' ')
{
temp += input[i];
}
else if (input[i] == ' ' && input[i + 1] != ' ')
{
temp += ch;
}
}
return temp;
}
You can use this code for your requirement
string tags = "This sample";
string cleanedString = System.Text.RegularExpressions.Regex.Replace(tags, @"\s+", "-");
Response.Write(cleanedString);
And result will be :
"This-sample"
I hope it will work for you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.