Tutorial :Please tell me what the problem is c# regex.split()



Question:

string temp_constraint = row["Constraint_Name"].ToString();  string split_string = "FK_"+tableName+"_";  string[] words = Regex.Split(temp_constraint, split_string);  

I am trying to split a string using another string.

temp_constraint = FK_ss_foo_ss_fee  split_string = FK_ss_foo_  

but it returns a single dimension array with the same string as in temp_constraint

Please help


Solution:1

Your split operation works fine for me:

string temp_constraint = "FK_ss_foo_ss_fee";  string split_string = "FK_ss_foo_";  string[] words = Regex.Split(temp_constraint, split_string);  foreach (string word in words)  {      Console.WriteLine(">{0}<", word);  }  

Output:

  ><  >ss_fee<  

I think the problem is that your variables are not set to what you think they are. You will need to debug to find the error elsewhere in your program.

I would also avoid using Split for this (both Regex and String.Split). You aren't really splitting the input - you are removing a string from the start. Split might not always do what you want. Imagine if you have a foreign key like the following:

FK_ss_foo_ss_fee_FK_ss_foo_ss_bee  

You want to get ss_fee_FK_ss_foo_ss_bee but split would give you ss_fee_ and ss_bee. This is a contrived example, but it does demonstrate that what you are doing is not a split.


Solution:2

You should use String.Split instead

string[] words =       temp_constraint.Split(new []{split_string}, StringSplitOptions.None);  


Solution:3

string split uses a character array to split text and does the split by each character which is not often ideal.

The following article shows how to split text by an entire word

http://www.bytechaser.com/en/functions/ufgr7wkpwf/split-text-by-words-and-not-character-arrays.aspx


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »