Click here to Skip to main content
15,914,488 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a string "Ram Vyas; Sham Dass; Suresh Khanna;"

I need to split the above string in such a way so that the resulting array containg

C#
arr[0] = "Ram Vyas"
arr[1] = "Sham Dass"
arr[2] = "Suresh Khanna"


currently i am using a string.split which causes

C#
arr[0] = "Ram Vyas"
arr[1] = " Sham Dass"
arr[2] = " Suresh Khanna"
arr[3] = ""


I am getting an extra space, How to avoid that?
Posted
Updated 13-Jun-13 23:20pm
v2

1 solution

Try:
C#
string[] arr = "Ram Vyas; Sham Dass; Suresh Khanna;".Split(new char[]{';'}, StringSplitOptions.RemoveEmptyEntries);
 
Share this answer
 
Comments
maverick12131 14-Jun-13 5:29am    
this solved the last entry arr[3] = "";
this is removed
but how to resolve the leading extra space in following
arr[1] = " Sham Dass"
arr[2] = " Suresh Khanna"


Also I have to remove any duplicate entries in the array
thanks
OriginalGriff 14-Jun-13 6:14am    
Both of those require additional processing: one is a simple Trim call, but the other needs either a slightly complex loop, or a quick use of Linq methods: so the easiest solution is to use Linq methods for both:
string[] arr = "Ram Vyas; Sham Dass; Suresh Khanna;Sham Dass;".Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
arr = arr.Select(s => s.Trim()).Distinct().ToArray();

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