The String.Split method returns an array of the substrings in a given string that are delimited by specified strings.
- using System;
- using System.Collections.Generic; // Only if you are using List<> in below example
- namespace ConsoleApplication1
- {
- public class MyClass
- {
- /// <summary>
- /// Using String.Split Method we will try to retrieve given string without delimiter value
- /// (delimiter: Means one which determine the limits or boundaries of something
- /// in this case query string word "where")
- /// and later in code we will return only Delimiter value i.e. "where".
- /// </summary>
- //Program Entry
- static void Main()
- {
- //Sample query string "myQuery"
- //Here we are using "where" as delimiter value
- //Our objective is to retrieve below string without "where" string.
- string myQuery = "select * from Customer where Cust_id=786";
- //---------------------------------------------------------
- //Array in which we will collect our string without delimiter (i.e. "where")
- string[] result; // OR List<string> result;// Also you can use generics List<> to
- //collect return set of strings.
- //---------------------------------------------------------
- //Here Overload of Split method is used with parameter "where"
- result = myQuery.Split(new string[] { "where" }, StringSplitOptions.None);
- //OR
- //result = myQuery.Split(new string[] { "where" }, StringSplitOptions.None).ToList();
- //If you are using generic list e.g.List<string> as above option.
- //As non of our returned arrays/list (e.g. result[0] and result[1])
- //contains empty string(s) in them we have selected
- //StringSplitOptions.None but if you suspect that there can be empty string then use
- //StringSplitOptions.RemoveEmptyEntries
- //---------------------------------------------------------
- //formatting outing by collecting 'result' array into str string
- //this step is required only for demonstration purpose of output
- string str = "";
- foreach (string s in result)
- str += s.Trim() +"\n";
- //---------------------------------------------------------
- Console.WriteLine("{0}", str);
- //Press Ctrl + F5: For Output.
- //OUTPUT
- // select * from Customer
- // Cust_id=786
- //---------------------------------------------------------
- //result[0] stores "select * from Customer" as string value
- //retult[1] stores "Cust_id=786" as string value
- Console.WriteLine("Result[0]= {0},\nResult[1]= {1}", result[0], result[1]);
- //---------------------------------------------------------
- //OUTPUT
- //Result[0]= select * from Customer ,
- //Result[1]= Cust_id=786
- //End of Program
- }
- }
- }