Reputation: 459
I want to replace string that start with specific character until first space space after that (or maybe first specific character) with another string.
For example If we have a string like this:
aaa bbb ccc @ddd eee fff @ggg hh#iii. jj
I want to make it something like this.
aaa bbb ccc @MMM eee fff @MMM hh#MMM. jj
I found a solution but that's not helpful for me.
UPDATE:
I want to replace all word that start with @
or #
and ended with or
.
or something else that I want with a string like MMM
.
In a real example I only know some work start with
@
or#
.
Upvotes: 0
Views: 1308
Reputation: 178
I think this would get a good start to what you are wanting, although may need some polish based on your specific needs.
string val = "aaa bbb ccc @ddd eee fff @ggg hh#iii. jj";
string[] values = val.Split(' '); //identify the separate entities you want split
val = "";//reset string to empty string
foreach(string a in values)
{
if (a.Contains('@') || a.Contains('#'))
val += a[0] + "MMM"; //change the values to 'M' of the original
else
val += a;
}
return val; //return the string with values changed to 'M'
Single line example using Linq as provided by Juharr in the comments
return string.Join(" ", val.Split().Select(s => s.StartsWIth('@') || s.StartsWith('#') ? s[0] + "MMM" : s));
Upvotes: 1
Reputation: 298
string example = "aaa bbb ccc @ddd eee fff @ggg hh"; //Init the input
string[] splitExample = example.Split(' '); //Split the string after every space into an array of substrings
for (int i = 0; i < splitExample.Length; i++) //Iterate through each substring
{
if (splitExample[i] != null) //Check if the currently tested string exists within the array
{
if (splitExample[i] == '@') // Test if the first char of the currently tested substring is '@'
{
splitExample[i] = "@MMM"
}
}
else
{
break; //Exit the loop if the tested string does not exist
}
}
string exampleOutput;
foreach(string append in splitExample) //Iterate through the array and add the now modified substrings back together
{
exampleOutput = exampleOutput + " " + append;
}
I'm not sure if this is the best way to do it, this was just off of my head
Upvotes: 0