Joshua Joshua - 3 months ago 14
C# Question

Using a method similar to Substring on a list of numbers

I have written a program that extracts all the possible sub-strings (contiguous subs) of a given strings:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace Empty
{
class Program
{
static void Main(string[] args)
{
string str = Console.ReadLine();

for (int i = 1; i <= str.Length; i++)
{
for (int j = 0; j <= (str.Length - i); j++)
{
string subStr = str.Substring(j, i);
Console.WriteLine(subStr);
}
}

Console.ReadLine();
}
}
}


So, when I enter
abc
, it returns:

a
b
c
ab
bc
abc


Now, I would like to use this idea to apply it to a list of integers, so that it returns all possible concatenations of the elements of this list of numbers.

For example, if I enter
[2 11 8]
, I would like it to return:

2
11
8
211
118
2118


Is there a method similar to
Substring
that I can use on a list of numbers to achieve my goal? In other words, can I re-use and modify my little program that works on a string, so it also works on a list of integers?

Answer

Is there a method similar to Substring that I can use on a list of numbers

Yes, there is a direct equivalent List<T> method called GetRange. You can see that by looking at the method signatures:

string: public string Substring(int startIndex, int length)

and

List<T>: public List<T> GetRange(int index, int count)

So, having List<int> list, replace str.Length with list.Count, str.Substring(j, i) with string.Concat(list.GetRange(i, j)) and you are done.

Comments