Reputation: 35
So i'm just wondering if anyone here can suggest a better solution for formatting the data in the string array so that it doesn't contain "," or ":"?
public void formatArrayInformation()
{
string[] readTxtFileAsOne = System.IO.File.ReadAllLines(@"C:\Users\test.txt");
string formatArrayString;
for (int i = 0; i < readTxtFileAsOne.Length; i++)
{
formatArrayString = readTxtFileAsOne[i];
string removeCommaInString = formatArrayString.Replace(":", " ");
formatArrayString = removeCommaInString.Replace(",", " ");
readTxtFileAsOne[i] = formatArrayString;
}
}
Upvotes: 1
Views: 82
Reputation: 48686
You could use Linq:
readTxtFileAsOne[i] = new string(readTxtFileAsOne[i]
.Where(c => !(new[] {',', ':'}).Contains(c)).ToArray());
To break it down, one of the constructors of string
allows you to pass in a character array and construct a string from the array of characters. This is what we are using.
We are breaking the string down into characters and creating a new array, skipping the ,
's and :
's. This new array gets created into a string using the string
constructor.
Upvotes: 0
Reputation: 7880
I don't see any problem with your approach. I would only simplify it like this:
public void formatArrayInformation()
{
string[] readTxtFileAsOne = System.IO.File.ReadAllLines(@"C:\Users\test.txt");
for (int i = 0; i < readTxtFileAsOne.Length; i++)
{
readTxtFileAsOne[i] = readTxtFileAsOne[i].Replace(":", " ").Replace(",", " ");
}
}
If instead of replacing them with spaces you want to just remove them, you can either, of course, use ""
as the second parameter for the Replace
method or do something weird like this:
public void formatArrayInformation()
{
string[] readTxtFileAsOne = System.IO.File.ReadAllLines(@"C:\Users\test.txt");
for (int i = 0; i < readTxtFileAsOne.Length; i++)
{
var txt = readTxtFileAsOne[i].ToList();
txt.RemoveAll(x => ":,".Contains(x));
readTxtFileAsOne[i] = new string(txt.ToArray());
}
}
Upvotes: 1
Reputation: 77876
You can make it in a single line like
string removeCommaInString = formatArrayString.Replace(":", "").Replace(",", "");
Upvotes: 1
Reputation: 344
Replace it by empty quotes ( replace(",","") or replace(":","") )
formatArrayString = readTxtFileAsOne[i];
string removeCommaInString = formatArrayString.Replace(":", "");
formatArrayString = removeCommaInString.Replace(",", "");
readTxtFileAsOne[i] = formatArrayString;
Upvotes: 0