This code should remove every third character and the last character from the String Data variable without the code knowing what characters the String Data contains.
The problem is that this code works well if the length of the String Data is 3 characters, but if it is more, then the characters to be deleted will not be deleted.
If I replace x == Data.Length
with x == 3
, then I get a runtime error if I run the code with more than three characters in the String Data variable.
int x = 0;
for (int i = 0; i < Data.Length; i )
{
x ;
if (x == Data.Length - i) //3
{
Data = Data.Remove(i, i - 1);
Data = Data.Remove(Data.Length - 1);
x = 0;
}
}
CodePudding user response:
You can try to use lambda Where
with your logic which will get an IEnumerable<char>
then passing in string construct method get the result.
var result = Data.Where((x,i)=> i%3 != 2 && i != Data.Length -1).ToArray();
Data = new string(result);
CodePudding user response:
You can accumulate the required characters into a StringBuilder, then chop off the last one:
string datum = "123456789";
var sb = new System.Text.StringBuilder();
for (int i = 0; i < datum.Length; i )
{
if (i % 3 != 2)
{
sb.Append(datum[i]);
}
}
sb.Length--; // Remove last char
datum = sb.ToString();
Console.WriteLine(datum);
Outputs:
12457
The way a StringBuilder works internally is more efficient than repeatedly concatenating to a string.
CodePudding user response:
You could take advantage of .Chunk()
, which lets you split up your string in chunks of (in your scenario) three chars, and of .SkipLast()
, which lets you skip the last char
in each chunk. In the end, join all char
s to create your output string.
var output = string.Join(string.Empty,
input.Chunk(3).SelectMany(ch => ch.SkipLast(1)));
The input
var input = "12345678901234567890123456789";
will produce
1245780134679023568
Both .Chunk()
and .SkipLast()
are found in the System.Linq
namespace.
Example fiddle here.
CodePudding user response:
Does this help?
for (int i = 0; i < Data.Length; i )
{
if((i 1)%3==0)
{
Data = Data.Remove(i, 1);
}
}
CodePudding user response:
I'd suggest using Linq Where() combined with the remainder operator to gather the chars that are at index 1 or 2, 4 or 5, etc:
var Data = "123456789abcdef";
Data = string.Join("", Data.Where((c, i) => (i 1) % 3 > 0));
Working .NET Fiddle: https://dotnetfiddle.net/DlSiiY
CodePudding user response:
Another one using a List<char>
and going backwards:
string input = "1234567890";
List<char> values = new List<char>(input.ToCharArray());
values.RemoveAt(values.Count - 1);
for(int i=(values.Count-1); i>=0; i--)
{
if ((i 1) % 3 == 0)
{
values.RemoveAt(i);
}
}
string output = new string(values.ToArray());
Console.WriteLine(" input: " input);
Console.WriteLine("output: " output);