views:

175

answers:

3

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 ///.

A: 

mainString.substring(mainString.IndexOf("Amount Rs. "), "///"), this should solve your problem I believe.

where mainString.IndexOf("Amount Rs. ") is the Start Index & "///" is the End Index.

Happy coding !!!!

Ravia
@Ravia,sorry but this gives the error...thanks for the help.
Harikrishna
+4  A: 

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);
Guffa
@Guffa,Great...sir..thanks for the help...It works....
Harikrishna
A: 
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.

joshcomley
You have put an @ before the first string literal, so it would look for `\/\/\/` rather than `///`. Besides, `\/` is not a valid escape sequence. You should use the `Regex.Escape` method on the `subString` value that you put in the regular expression for it to be safe for any value.
Guffa