RLE Compression method

142 Views Asked by At
Console.WriteLine("Enter the string you would want to compress using RLE format");

string UserInput = Console.ReadLine();
int repitions = 1;

for (int i = 0; i < UserInput.Length; i++)
{
    if (UserInput[i] == UserInput[i + 1])
    {
        repitions++;
    }
    else
    {
        Console.WriteLine("{0}{1}", repitions, UserInput[i]);
        repitions = 1;
    }
}

In line 5, there is an error where it says

index was outside the bounds.

My aim is to use this compression and output the number of times the characters repeats and the type of character then move onto the next. Im not sure what is wrong here.

Im expecting a proper working RLE algorithm.

1

There are 1 best solutions below

2
Dmitry Bychenko On

The immediate reason of the exception is in

if (UserInput[i] == UserInput[i + 1])

comparions: on last character of the UserInput, i == UserInput.Length - 1 and we have index out of range at UserInput[i + 1]. We have to add an extra check for the last character:

Console.WriteLine("Enter the string you would want to compress using RLE format");
string UserInput = Console.ReadLine();

for (int i = 0, count = 1; i < UserInput.Length; ++i) 
  if (i < UserInput.Length - 1 && UserInput[i] == UserInput[i + 1])
    count += 1;
  else {
    // You, probably, want to get one line string (Write instead of WriteLine)
    Console.Write($"{count}{UserInput[i]}");
    
    count = 1;
  }

A more maintable approach is to extract method for RLE:

private static string ToRle(string value) {
  if (string.IsNullOrEmpty(value))
    return value;

  StringBuilder sb = new SringBuilder(value.Length * 2);

  for (int i = 0, count = 1; i < UserInput.Length; ++i) 
    if (i < UserInput.Length - 1 && UserInput[i] == UserInput[i + 1])
      count += 1;
    else {
      sb.Append(count);
      sb.Append(UserInput[i]);
    
      count = 1;
    }
  }

  return sb.ToString();
}

And then use it:

Console.WriteLine("Enter the string you would want to compress using RLE format");
string UserInput = Console.ReadLine();

Console.WriteLine(ToRle(UserInput));