Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ForEach to Trim string values in string array

I just wondered why this ForEach doesn't work and leaves the values with trailing whitespace.

string days = "Monday, Tuesday, Wednesday, Thursday, Friday";

string[] m_days = days.Split(',');

m_days.ToList().ForEach(d => { d = d.Trim(); } );

I know there are other ways of doing this so i don't need and answer there.

like image 960
David Avatar asked Feb 15 '13 12:02

David


People also ask

Can we trim string?

The trim() method in Java String is a built-in function that eliminates leading and trailing spaces. The Unicode value of space character is '\u0020'. The trim() method in java checks this Unicode value before and after the string, if it exists then removes the spaces and returns the omitted string.


1 Answers

Because you are not reassigning the trimmed strings.

var list = m_days.Split(',').Select(s => s.Trim()).ToList();

Why ForEach doesn't work or if I am using the ForEach incorrectly?

ForEach is not Linq, it's a method of List<T>. What you are doing is basically this:

foreach(string day in m_days)
{
    day.Trim();  // you are throwing away the new string returned by String.Trim
}

Instead of using LINQ you could also use a for-loop instead:

for(int i = 0; i < m_days.Length; i++)
{
    m_days[i] = m_days[i].Trim();
}
like image 126
Tim Schmelter Avatar answered Nov 02 '22 20:11

Tim Schmelter