Reputation: 4305
How can we divide the substring from the string
Like I have string
String mainString="///Trade Time///Trade Number///Amount Rs.///";
Now I have other string
String subString="Amount"
Then I want to extract the substring Amount Rs.
with the help of second string named subString not by any other method But it should be extracted through two parameters like first is I have index no of Amount string and second is until the next string ///.
Upvotes: 18
Views: 60573
Reputation: 9942
This should solve your problem I believe:
mainString.substring(mainString.IndexOf("Amount Rs. "), "///")
where mainString.IndexOf("Amount Rs. ")
is the Start Index
& "///"
is the End Index.
Upvotes: 1
Reputation: 18600
As a compliment to @Guffa's answer, you can make an extension method out of it:
Note: There's no validation to ensure that the provided indexes are in the bounds of the string.
public static class StringExtensions
{
public static string SubstringBetweenIndexes(string value, int startIndex, int endIndex)
{
return value.Substring(startIndex, endIndex - startIndex);
}
}
Upvotes: 2
Reputation: 28818
string str = Regex.Match("///(?<String>[^/]*?" + subString + "[^/]*?)///").Groups["String"].Value;
Should use String.Format
but the exact usage of {x}
in an @ string win a Regex I can't remember (do you need to double up the {}
?)
N.B: This assumes you are not expecting any /
, so could be improved a little.
Upvotes: 1
Reputation: 700272
First get the index of the substring:
int startIndex = mainString.IndexOf(subString);
Then get the index of the following slashes:
int endIndex = mainString.IndexOf("///", startIndex);
Then you can get the substring that you want:
string amountString = mainString.Substring(startIndex, endIndex - startIndex);
Upvotes: 35