Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the equivalent of Java substring in C#?

Tags:

substring

c#

When I want to do a substring to find a region of text in a string in Java, I supply two indexes, one for the start, and one for the end, but in C#, I am forced to provide length of the substring as a parameter, however this becomes a problem if I don't know where I'm supposed to stop, leading me to have things like this:

verse[i].Substring(verse[i].IndexOf("start"), (verse[i].IndexOf("end") - verse[i].IndexOf("start"));

instead of just

verse[i].Substring(verse[i].IndexOf("start"), (verse[i].IndexOf("end"));

Annoyingly I have come across this issue over and over again and I wonder if I'm the only one or there's a trick I'm not aware of. How best would you go about solving this issue? (Taking cleanliness and speed into consideration)

ps: I don't like creating variables for nearly everything. Thanks

like image 639
rtuner Avatar asked Dec 04 '22 01:12

rtuner


2 Answers

The answer you accepted is wrong, because you asked it wrong.

In java when you call substring(START, END) you get a substring starting at START and ending at END - 1.

in c# you just have to call like:

Substring(START, END - START);

If you add 1 as suggested, you will get a different string.

like image 165
nightshade Avatar answered Dec 20 '22 17:12

nightshade


You can write your own extension method like this

var newstr = str.MySubString(start,end);

..

public static partial class MyExtensions
{
    public static string MySubString(this string s,int start,int end)
    {
        return s.Substring(start, end - start + 1);
    }
}
like image 29
L.B Avatar answered Dec 20 '22 17:12

L.B