1
string = "This is a test string. It has 44 characters." #Line1
for i in range(len(string) // 10):                      #Line2
    result= string[10 * i:10 * i + 10]                  #Line3
    print(result)                                       #Line4

I want to understand the above code so that I can achieve the same thing using C#

According to my understanding, in Line2:

len(string) counts the length of above string which is 44, dividing by 10 returns 4, range(4) should return: 0,1,2,3 so the for loop will run 4 times to print result

I confirmed how Line3 works by adding below statements in the python code:

print(string[0:10])
print(string[10:20])
print(string[20:30])
print(string[30:40])

The output of both were:

This is a 
test strin
g. It has 
44 charact

I tried the below code in C# to achieve the same which didn't print anything:

string str = "This is a test string. It has 44 characters.";


            foreach (int i in Enumerable.Range(0, str.Length / 10))
            {
                string result = str[(10*i)..(10*i+10)];
                Console.WriteLine(result);
            }
Andy
  • 919
  • 2
  • 9
  • 22
hellouniverse
  • 113
  • 1
  • 12

2 Answers2

0

This is how you slice strings in C# with Substring:

string str = "This is a test string. It has 44 characters.";

foreach (int i in Enumerable.Range(0, str.Length / 10))
{
    var start = 10 * i;
    var end = 10 * i + 10;
    Console.WriteLine(str.Substring(start, end));
}

....but you may need to adjust the numbers and check for Index / Out Of Range exceptions.

JacobIRR
  • 8,545
  • 8
  • 39
  • 68
0

you just translate the slice method with substring:

public string Slice(string source, int start, int end)
{
    if (end < 0) // Keep this for negative end support
    {
        end = source.Length + end;
    }
    int len = end - start;               // Calculate length
    return source.Substring(start, len); // Return Substring of length
}

Testing the method:

var string = "This is a test string. It has 44 characters."
var result = Slice(string, 0, 10);//give the first tenth chars and so on...
Console.WriteLine(result);
Frenchy
  • 16,386
  • 3
  • 16
  • 39