I have an array and a variable :
string[] StringArray = { "foo bar foo $ bar $ foo bar $" };
string check = "$";
And I want to remove the "$" so the output will be :
foo bar foo bar foo bar
CodePudding user response:
How about using linq?
string[] StringArray = { "foo bar foo $ bar $ foo bar $" };
string check = "$";
var noDollaBillsYall = StringArray.Select(x => x.Replace(check, string.Empty)).ToArray();
CodePudding user response:
You could iterate across the array with a for each, and use replace to replace the $ character with nothing.
for(int i = 0;i < StringArray.Length;i ) {
StringArray[i] = StringArray[i].Replace(“$”,””);
}
I can’t guarantee that this will work by itself, as I am not at my computer, but this is the basic idea.
CodePudding user response:
i would try using a foreach to loop around the array and a stringBuilder. inside the foreach write if(element == '$') continue. else append it to the string builder.
if you wanna try this i'd write u the code lmk
CodePudding user response:
If you are trying to initialize an array with multiple string
, then your initialization is wrong, if that is the case, this implementation should work:
string[] StringArray = { "foo", "bar", "foo", "$", "bar", "$", "foo", "bar", "$" };
string check = "$";
var stringList = StringArray.ToList();
stringList.RemoveAll(x => x == check);
StringArray = stringList.ToArray();
CodePudding user response:
Found an answer. I use .Replace to remove the desired character. This is my solution :
string[] StringArray = { "foo bar foo $ bar $ foo bar $" };
foreach(var result in StringArray)
{
Console.WriteLine(result.Replace('$',' ').ToString());
}
Maybe any of you find more efficient way, I'm really appreciate it if you would to tell me
CodePudding user response:
Quite an intersting task; assuming that you want to process each item we can use Linq.
Another problem is it seems that we can't just replace / remove $
: we should control
spaces as well, e.g.
Given:
"$ foo bar foo $ bar $ foo bar $"
Naive removing: (e.g. item => item.Replace("$", string.Empty)
)
" foo bar foo bar $ foo bar " <- note spaces
Actual requirement:
"foo bar foo bar foo bar"
We can cope with spaces with a help of Regular Expressions:
using System.Linq;
using System.Text.RegularExpressions;
...
string[] StringArray = { "$ foo bar foo $ bar $ foo bar $" };
string[] result = StringArray
.Select(item => Regex.Replace(
item,
@"\s*\$\s*",
m => m.Index == 0 || m.Index m.Length == item.Length ? "" : " "))
.ToArray();