Zsombor V
Zsombor V

Reputation: 19

Alternatingly remove each character from a string returning the rest as one per loop

Example input string is "12345" the result should be: "2345, 1345, 1245, 1235, 1234". I have tried Substring and Remove alone and in combinations with halfway success. I would prefer to not have to manually put & manipulate the string's elements in a list/array, and to keep the solution within basic String operations, if at all possible. This was my latest attempt:

using System;
                    
public class Program
{
    public static void Main()
    {
        string message = "12345"; // length: 5
        string removed; int i = 0;
        
        removed = message.Substring(i+1); Console.WriteLine("1: " + removed);

        for(i = 2; i < message.Length; i++) {
            removed = message.Substring(i);
        
            Console.WriteLine(i + ": " + removed);
        }

        removed = message.Substring(i); 
        
        Console.WriteLine(i + ": " + removed);
    }
}

@Mureinik Thank you for your solution. I chose it for its simplicity.

I also realized going through it that I may have messed up my index iteration for Remove the first time I tired using it; that's why it kept throwing the exceptions.

I have decided to leave my code here as reference for my explanation and because the solution I chose looks different.

Upvotes: 0

Views: 49

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

Well, you can do it either with a help of Remove:

private static IEnumerable<string> Removes(string value) {
  if (string.IsNullOrEmpty(value))
    yield break;

  for (int i = 0; i < value.Length; ++i)
    yield return value.Remove(i, 1);
}

Or Substring (a bit less efficient):

private static IEnumerable<string> Removes(string value) {
  if (string.IsNullOrEmpty(value))
    yield break;

  for (int i = 0; i < value.Length; ++i)
    yield return value.Substring(0, i) + value.Substring(i + 1);
}

Demo:

Console.Write(string.Join(", ", Removes("12345")));

Outcome:

2345, 1345, 1245, 1235, 1234

Upvotes: 3

Mureinik
Mureinik

Reputation: 311188

One option is to create a new StringBuilder in every iteration of the loop, and use it to remove a character:

string message = "12345"; // length: 5
for (int i = 0; i < message.Length; ++i) {
    StringBuilder sb = new StringBuilder(message);
    sb.Remove(i, 1);
    Console.WriteLine(sb);
}

Upvotes: 1

Related Questions