get the length of all substrings in csharp

You can get the length of all possible substrings of a given string in C# by using nested loops and the Substring method.

main.cs
string str = "hello";
int n = str.Length;

// Initialize an array to store the lengths of all substrings
int[] substrLen = new int[n*(n+1)/2];
int k = 0;

// Nested loops to generate all possible substrings of the string
for (int i = 0; i < n; i++)
{
    for (int j = i; j < n; j++)
    {
        // Get the substring from i to j
        string sub = str.Substring(i, j - i + 1);

        // Get the length of the substring and store it in the array
        int len = sub.Length;
        substrLen[k++] = len;
    }
}

// Print the lengths of all substrings
for (int i = 0; i < k; i++)
{
    Console.WriteLine(substrLen[i]);
}
627 chars
27 lines

In this code, we first initialize an array substrLen to store the lengths of all possible substrings. We then use nested loops to generate all possible substrings of the given string. For each substring, we use the Substring method to extract it from the original string, and then we get its length and store it in the substrLen array. Finally, we print the lengths of all substrings by iterating over the array.

related categories

gistlibby LogSnag