Reputation: 8646
I have string as :
string sku= "plmca60 5";
I just wanted to replace first blank space with comma. Hence I tried:
sku.replace(" ",",");
But it given me:
sku="plmca60,,,,,5";
Its because five blank spaces are there in the string. But I want to replace just first occurrence of blank space like;
sku="plmca60, 5"
How can I do like this?
Upvotes: 0
Views: 4101
Reputation: 4659
I would capture 1 space with 0 or more spaces after that in a capture group. That way you can replace it with a comma and the content of the capture-group (which was any spaces after the first one)
Regex.Replace(input, @"\s(\s*)", ",$1");
Upvotes: 1
Reputation: 1574
Two line version:
string sku = "plmca60 5";
Console.WriteLine(sku.Insert(sku.IndexOf(" ")).Remove(sku.Index(" "));
Upvotes: 0
Reputation: 890
string sku = "plmca60 5";
int pos = sku.IndexOf(" ");
char[] a = sku.ToCharArray();
a[pos]=a[pos].ToString().Replace(" ", ",").ToCharArray()[0];
var result = new string(a);
This is dirty way. Meanwhile trying to find out shorter way of doing this.
Upvotes: 1
Reputation: 98868
First of all, String.Replace
method1 returns your string as plmca60,,,,,5
because from documentation;
Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.
You don't need regex for that.
You can use String.IndexOf(string)
to get first index of a white space and a little bit Remove
and Insert
methods combination.
Reports the zero-based index of the first occurrence of the specified string in this instance
string sku = "plmca60 5";
int index = sku.IndexOf(" ");
sku = sku.Remove(index, 1).Insert(index, ",");
Console.WriteLine(sku);
Result will be;
plmca60, 5
Here a demonstration
.
1: Remember, it is Replace
, not replace
. C# is case sensitive language.
Upvotes: 5
Reputation: 22321
By using Regex.Replace
var regex = new Regex(Regex.Escape(" "));
var newText = regex.Replace("plmca60 5", ",", 1);
Upvotes: 2
Reputation: 174874
You could use capturing groups like below,
@"^(\S*)\s"
OR
@"^(\S*) "
Replace the matched space by,
$1,
\S
matches a non-whitespace character. \S*
matches zero or more non-whitespace characters. ^
asserts that we are at the start.
Code:
string sku= "plmca60 5";
string result = Regex.Replace(sku, @"^(\S*) ", "$1,");
Console.WriteLine(result);
Console.ReadLine();
Upvotes: 3
Reputation: 7102
You can replace all whitespace with ", ". For example:
sku = Regex.Replace(sku, @"\s+", ", ");
Upvotes: 1
Reputation: 4038
Not an optimized solution but it works,
string sku = "plmca60 5";
string[] skyArr = sku.Split(' ');
skyArr[1] = ",";
string resultString = "";
foreach (string str in skyArr)
{
if (str == "")
resultString += " ";
else
resultString += str;
}
}
Console.WriteLine(resultString);
Upvotes: 1