[ACCEPTED]-Remove multiple char types from end of string-string
returnValue = returnValue.TrimEnd(' ', ',');
0
You should also avoid using strings in your 4 case, instead use StringBuilder. Avoid also 3 using senseles formatting -just list[iRow] is 2 a better option.
Try something like this 1 instead:
string result = string.Join(", ",
list.Where(s => !string.IsNullOrEmpty(s)).ToArray());
string's TrimEnd static method allows to 5 specify which characters should be trimmed.
However, in 4 your case it would make sense to check in 3 the for loop whether you have empty slots, and 2 at the end put together a resulting string 1 with string.Join(string separator, string[] parts)
If you want to remove something you added, don't 3 add them in the first place. Also, the StringBuilder
type 2 is better suited for concatenating multiple 1 strings, as it much more memory efficient.
StringBuilder sb = new StringBuilder();
for (int i = 0; i < list.Count; i++)
{
string rowValue = list[iRow];
if (!string.IsNullOrEmpty(rowValue))
{
sb.Append(rowValue);
sb.Append(", ");
}
}
// use sb.ToString() to obtain result
I hate to make assumptions, but I will because 9 it seems you want preserve the "gaps" until 8 you get to the end, in which case you should 7 use TrimEnd. If not, then use any one of 6 the other options to avoid adding the empty 5 values in the first place.
More precisely 4 if your output could look like:
asd, aaa, qwe, 123123, , , somevalue 3 , ,
Then you'll have to loop through and 2 use TrimEnd.
Otherwise, if you can collapse 1 the fields then exclude the empties upfront.
asd, aaa, qwe, 123123, somevalue
try this:
List<string> list = new List<string>(
new string[]{"asd", "aaa", "qwe", "123123", "", null, "", null, ""});
return String.Join(", ", list.Where(i => !String.IsNullOrEmpty(i)).ToArray());
0
I realise that this is quite unreadable 1 AND is wasteful but (without linq):
return string.Join(" ,",string.Join(", ",list.ToArray()).Split(", ", StringSplitOptions.RemoveEmptyEntries));
Found this, time for a better answer.
Try 5 this:
returnValue = returnValue.TrimEnd(", ".ToCharArray());
You can convert a regular string to 4 a char array and all those chars will be 3 trimmed.
However, There are more problems. See 2 comments in code below:
string returnValue 1 = "";
for (int iRow = 0; iRow < list.Count; iRow++) //start from 0 not 1
{
//returnValue += String.Format("{0}, ", list[iRow]);
if(string.IsNullOrEmpty(list[iRow]) == false) //still allow space as valid entry...
{
//the list is already a list of strings, no reason to convert string to string.
returnValue += list[iRow] + ", ";
}
}
//alternatively try this, it will do all the work for you:
//returnValue = string.Join<string>(", ", list);
//deal with trailing comma and space at end:
returnValue = returnValue.TrimEnd(", ".ToCharArray());
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.