Asked by:
Extract Values from a string

Question
-
User-1499457942 posted
Hi
I have a string like this C01_P_Usr_abc.xls . I want to extract string between second _ and third _ . In this case it should give Usr.
Thanks
Sunday, June 24, 2018 8:49 AM
All replies
-
User1120430333 posted
Sunday, June 24, 2018 10:22 AM -
User36583972 posted
Hi JagjitSingh,I have a string like this C01_P_Usr_abc.xls . I want to extract string between second _ and third _ . In this case it should give Usr.You can try the following methods.
1: Use Split and get the values.
string tet = "C01_P_Usr_abc.xls"; string[] myAgent = tet.Split(new string[] { "_" }, StringSplitOptions.None); for (int i =0; i <myAgent.Length; i++) { Console.WriteLine(myAgent[i].ToString()); }
2: Substring
string tet = "C01_P_Usr_abc.xls"; //int getfirstindex = 3;//abc int getfirstindex = 2;//User //int getfirstindex = 1;//P string result = ""; for(int i =0; i <= getfirstindex; i ++) { if(i == getfirstindex) { if(result=="") { result = tet.Substring(0, tet.IndexOf('_')); } else { try { result = result.Substring(0, result.IndexOf('_')); } catch { result = result.Substring(0, result.IndexOf('.')); } } } else { if (result == "") { result = tet.Substring(tet.IndexOf('_') + 1); } else { try { result = result.Substring(result.IndexOf('_') + 1); } catch { result = result.Substring(0, result.IndexOf('.')); } } } }
Best Regards,Yong Lu
Monday, June 25, 2018 8:32 AM -
User1341756031 posted
Try...C# substring method
Wednesday, January 2, 2019 6:04 AM -
User738333362 posted
// Main Method public static void Main() { // define string String str = "GeeksForGeeks"; Console.WriteLine("String : " + str); // retrieve the substring from index 5 Console.WriteLine("Sub String1: " + str.Substring(5)); // retrieve the substring from index 8 Console.WriteLine("Sub String2: " + str.Substring(8)); }
Thursday, January 3, 2019 7:36 AM