Click here to Skip to main content
15,901,122 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

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

currently i am using a string.split which causes

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

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

1 solution

string[] arr = "Ram Vyas; Sham Dass; Suresh Khanna;".Split(new char[]{';'}, StringSplitOptions.RemoveEmptyEntries);
Share this answer
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
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