How can we extract substring of the string by position and separator
How can we divide the substring from the string
Like I have string
String mainString="开发者_StackOverflow社区///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 ///.
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);
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.
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);
}
}
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.
精彩评论