Click here to Skip to main content
15,900,816 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I just had a question. I want to let the user enter a number of characters/numbers in a TextBox separated by commas and then the code to read it in a way so that each element in the TextBox separated by the comma is a separate element in an array into which I want to input those characters/numbers.
For example: Input: 12, good, 5
Elements in the array:{12, "good", 5};

I hope everyone understood my question and will be able to help me.
Thanks.
Posted

C#
object[] array = textBox1.Text.Split(',');
 
Share this answer
 
Easy:
C#
string s = "12,good,5";
string[] parts = s.Split(',');

If you also need to remove spaces:
C#
string s = "12, good, 5";
string[] parts = s.Split(',').Select(p => p.Trim()).ToArray();
 
Share this answer
 
Comments
Anas Tasadduq 4-May-14 3:05am    
What is the meaning of "=>" over here? and what is p?
I'm a beginner programmer so sorry for these questions.
OriginalGriff 4-May-14 3:20am    
It's what's called a "lambda expression" and you will meet them later on in your course.
For the moment, ignore them, and do it this way:
string[] parts = s.Split(',');
for (int i = 0; i < parts.Length; i++)
{
parts[i] = parts[i].Trim();
}
You'll understand what I'm doing when you get to Linq, but I don't want to confuse you by explaining something you aren't ready for yet, and won't meet for weeks!
Just think of it as a "shorthand" for the loop (it isn't, but it'll do as an explanation for the moment)
Anas Tasadduq 4-May-14 3:24am    
Thanx very much!
OriginalGriff 4-May-14 3:32am    
You're welcome!

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