I need help on remove tailing 0 from comma separated string using c#
my data is string = "110, 0, 170, 0, 0"
output needed string = "110, 0, 170"
Help is appreciated,
CodePudding user response:
Here you go, I chained multiple Linq Methods to achieve the goal.
using System;
using System.Linq;
var input = "110, 0, 170, 0, 0";
var splittedInput = input.Split(", ");
var resultArray = splittedInput.Reverse().SkipWhile(e => Convert.ToInt32(e) == 0).Reverse();
var result = string.Join(", ", resultArray);
And you have the result in the result variable. I suggest you take a look at : SkipWhile, Reverse, and Convert.ToInt32()
CodePudding user response:
Here is one way of doing it.
var input = "110, 0, 170, 0, 0";
while (input.EndsWith(", 0"))
{
input = input.Substring(0, input.Length - 3);
}
//input will now have the desired output 110, 0, 170
CodePudding user response:
My 2 cents: Keep on searching from right to left until non zero item is found
void Main()
{
string s = "110, 0, 170, 0, 0";
//string s = "110, 0, 170";
//string s = "110";
Trimmer t = new Trimmer();
var result = t.RTrimZero(s);
Console.WriteLine(result);
}
public class Trimmer
{
public string RTrimZero(string s)
{
bool IsEndingWithZero = false;
Tuple<string, bool> result = null;
do
{
result = CutIT(s);
s = result.Item1;
}
while (result.Item2 == true);
return s;
}
private Tuple<string, bool> CutIT(string s)
{
string collected = string.Empty;
for (var x = s.Length - 1; x >= 0; x--)
{
char cur = s[x];
if (cur.Equals(','))
{
//Console.WriteLine(collected);
int val = Convert.ToInt32(collected);
if (val == 0)
{
//cut it
return new Tuple<string, bool>(s.Substring(0, x), true);
}
else
{
return new Tuple<string, bool>(s, false);
}
}
else
{
collected = s[x] collected;
}
}
return new Tuple<string, bool>(s, false);
}
}