0

in java the substring function(index,lenght) the index can be higher then lenght

System.out.print("BCDABCD".substring(3 , 7));

this output "ABCD"

i dont want this

Console.Writeline("BCDABCD".substring(3 , 4));

for ex if i want to generate this :

for i = 0 to 63 {Console.Writeline("BCDABCD".substring(i , i + 1 )));

how to do that in c# ?

1 Answer 1

4

The second parameter of String.substring(int, int) in Java isn't the length - it's the (exclusive) upper bound of the index. Whereas in .NET, the second parameter of String.Substring(int, int) really is a length.

So any time you call foo.substring(x, y) in Java, that's equivalent to foo.Substring(x, y - x) in .NET... and you really need to take that into account.

It's not really clear what you're trying to do, but your loop wouldn't work in Java either. If you really want to just get a single character from the string, just use the indexer along with %:

string text = "BCDABCD";
for (int i = 0; i < 63; i++)
{
    Console.WriteLine(text[i % text.Length]);
}

EDIT: Given the comment, I suspect you just want:

for (int i = 0; i < 63; i++)
{
    Console.WriteLine("BCDABCD".Substring(3 - (j & 3), 4));
}

... in other words, the length will always be 4.

Sign up to request clarification or add additional context in comments.

4 Comments

in java here is my function for (int j = 0; j < 64;j++) { "BCDABCD".substring(3 - (j & 3), 7 - (j & 3))} how to do that with the answer solution ?
@studentofmp: See my edited answer. (It would have helped if you'd told us what output you actually want...)
in java my code works it generates : ABCD DABC CDAB BCDA X
@studentofmp: Right. You should get the same output from my code (second snippet).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.