How can we extract a substring of a string by position and delimiter

How can we split a substring into a string

Like a string

String mainString="///Trade Time///Trade Number///Amount Rs.///";

Now i have another line

String subString="Amount"

Then I want to extract the substring Amount Rs.using the second line named subString not by any other method. But it must be extracted from two parameters, for example, I have an index of no of Amount line and the second to the next line ///.

+5
source share
4 answers

First get the substring index:

int startIndex = mainString.IndexOf(subString);

Then get the index of the following slashes:

int endIndex = mainString.IndexOf("///", startIndex);

Then you can get the substring you need:

string amountString = mainString.Substring(startIndex, endIndex - startIndex);
+18
source

This should solve your problem, I believe:

mainString.substring(mainString.IndexOf("Amount Rs. "), "///")

mainString.IndexOf("Amount Rs. ") - & ; "///" - .

+1
string str = Regex.Match("///(?<String>[^/]*?" + subString + "[^/]*?)///").Groups["String"].Value;

Should use String.Format, but the exact use {x}in the @ line causes a Regex that I don't remember about (do you need to double the value {}?)

NB: It is assumed that you are not expecting any /, so it can be improved a bit.

+1
source

As a compliment to @Guffa's answer, you can make an extension method out of it:

Note. There is no check to ensure that the provided indexes are within row boundaries.

public static class StringExtensions
{

    public static string SubstringBetweenIndexes(string value, int startIndex, int endIndex)
    {
        return value.Substring(startIndex, endIndex - startIndex);
    }

}
0
source

All Articles