Well, O(n**2)time complexity is inevitable, however you can try to use space consumption. In many cases, you do not want all substrings to be implemented, for example, like List<string>:
public static IEnumerable<string> AllSubstrings(string value) {
if (value == null)
yield break;
for (int length = 1; length < value.Length; ++length)
for (int start = 0; start <= value.Length - length; ++start)
yield return value.Substring(start, length);
}
For example, let us count all the substrings in "abracadabra"starting with aand longer than 3characters. Please note that all we need to do is iterate over the subkeys without saving them in the list:
int count = AllSubstrings("abracadabra")
.Count(item => item.StartsWith("a") && item.Length > 3);
If for any reason you want List<string>, just add .ToList():
var stringList = AllSubstrings(mainString).ToList();
source
share