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
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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With