What is equivalent to Java substring in C #?

When I want to do a substring to find a region of text in a string in Java, I will put two indexes: one for start and one for end , but in C # I force the substring length to be provided as a parameter, however this becomes a problem if I don't know where should I stop, which will lead me to the following things:

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

instead

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

Annoyingly, I have come across this problem over and over again and I am wondering if I am the only one or is there a trick I don’t know about. How could you solve this problem best? (Considering cleanliness and speed)

ps: I don't like creating variables for almost anything. Thanks

+4
source share
4 answers

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); } } 
+9
source

The answer you accepted is wrong because you were wrong.

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

in C # you just need to call like:

 Substring(START, END - START); 

If you add 1 as suggested, you will get another line.

+6
source

The OP asked, "What is equivalent to a Java substring in C #"? I was glad to see the answer, since I converted the Java method that used String.substring to C #. However, according to official Java docs , the Substring begins with the specified beginIndex and continues to the character in index endIndex -1 This was not just a minor difference for me, since I wanted to convert Java with C # with the least effort. The extension mentioned above is a great answer, and of course I could handle it. But for my needs, a more accurate version like Java should be returned by s.Substring (start, end-start); do not start + 1

Using Java doc examples, the test shows that this is correct:

 [TestMethod] public void TestSubString() { Assert.AreEqual("urge", "hamburger".MySubstring( 4, 8)); Assert.AreEqual("mile", "smiles".MySubstring(1, 5)); } 
+2
source

Try using this extension method:

 public static class StringExtensions { public static string MySubstring(this string s, string start, string end) { int startI = s.IndexOf(start); int endI = s.IndexOf(end, startI); return s.Substring(startI, endI - startI + 1); } } 

Use it as follows:

 string helloWorld = "startHello Worldend".MySubstring("start", "end"); string vers = verse[i].MySubstring("start", "end"); 

Sometimes extension methods save your life. You only need to know that if the static class is public and in your namespace, everyone who uses your namespace also gets your extensions.

0
source

All Articles