Click here to Skip to main content
15,890,527 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,

i have a string variable like below


C#
string strdata = "MobileP: 9712899082P: 123654789FaxG: 0265123456EmailG: abc@gmail.com";



now i want to split data into array like below


C#
string[] arraydata = {"MobileP: 9712899082","P: 123654789","FaxG: 0265123456","EmailG: abc@gmail.com"};


once i get this array i can further split this by ":" and get data which i want.
can someone please help me how to solve this ?
Posted
Updated 22-May-14 21:25pm
v2

C#
var strdata = "MobileP: 9712899082P: 123654789FaxG: 0265123456EmailG: abc@gmail.com";
var values  = strdata.Split(new string[]{"MobileP: ", "P: ", "FaxG: ", "EmailG: "},  
                           System.StringSplitOptions.RemoveEmptyEntries).ToArray();

now you can use the values as below
C#
var MobileP = values[0];
var P = values[1];
var FaxG = values[2];
var EmailG = values[3];
 
Share this answer
 
v2
Comments
CPallini 23-May-14 3:53am    
5.
DamithSL 23-May-14 3:58am    
Thanks you CPallini
ravikhoda 23-May-14 4:56am    
thanks this works like a charm :) +5
DamithSL 23-May-14 4:58am    
you are welcome!
Animesh Datta 23-May-14 5:28am    
my 5!
Try this

C#
string input = "MobileP: 9712899082P: 123654789FaxG: 0265123456EmailG: abc@gmail.com";
string pattern = @"(\w+:\s\d+)";
string[] substrings = Regex.Split(input, pattern);
List<string> result = substrings.Where(item => item != "").ToList() ;
foreach (string match in result)
{
   Console.WriteLine("'{0}'", match);
}
 
Share this answer
 
v2
Use the string's split [^] method and split on space.
You can pass a string [] as parameter so optionally you could pass " " and ":"...

C#
string [] arraydata = strdata.split(new string[]{" "}, StringSplitOptions.None);


Hope this helps.
 
Share this answer
 
Comments
ravikhoda 23-May-14 3:37am    
this will give me output like below

string [] arraydata = {"MobileP:","9712899082P:","123654789FaxG:","0265123456EmailG:","abc@gmail.com"};

which will not work. what is the thing is mobilep,faxg,emailg are my keywords(i can use a space to separate that)but this structure is coming from some third party so can not change it. one more thing the order of the data is also not fixed it may be possible that faxg comes first and then come emailg and so on..
V. 23-May-14 4:08am    
I see, but in that case you only need to change the array you pass into the split method like DamithSL showed...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900