Click here to Skip to main content
15,895,986 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have a variable which is being populated with names from an excel spreadsheet. The names however were manually entered and because of that don't have the best format.

How can use
C#
string.split
or
C#
substring
to account for some of the following examples:

"J ane Doe"
"John Smith"

I've taken a look at the msdn examples but didn't quite understand them. When I debug my code the variable Worker = "John Smith" but I'd like to break the word into first and last name while also trimming any excess spaces.

Any ideas?
Posted
Comments
[no name] 4-Aug-15 18:24pm    
You could not understand string.Split(new Char[]{' '})? What is the difficulty?
Member 11820531 4-Aug-15 18:40pm    
The syntax and what each piece of code is doing. Take your example, I read it as: string.Split a new array of datatype Char. Split where there is an empty space. Is that what the code you posted is intended to do?
[no name] 4-Aug-15 20:56pm    
Why don't you try it and find out for yourself what it does? That is what the debugger is for.
Ralf Meier 5-Aug-15 0:51am    
Both commands do exactly what their Name says.
Split : it divides a given String into parts. For this you have to tell it which the char (or string-part) is where split should take Action. The result is an Array of string-parts (or the source-string itself if there was nothing to split).

SubString : builds a part of the source-string by the coordinates you give it.

But in fact it is the best to try it by yourself, what these commands do and perhaps what they do not ...
Patrice T 4-Aug-15 19:18pm    
Find more examples and put them in your debugger until you underdtand.
read language documentation.
post real code

1 solution

If you want to break "John Smith" into "John", "Smith" and "J ane Doe" into "J ane", "Doe" then split is not for you - it will always split on each space, for "J ane Doe" will become "J", "ane", "Doe".


Substring can do it:


C#
string input = "J ane Doe";
int lastSpace = input.LastIndexOf(' ');
string firstName = input.SubString(0, lastSpace);
string lastName = input.Substring(lastSpace);

Or you could use a Regex:
(?<firstName>.*)\s(?<lastName>[A-Z][a-zA-Z-]*)$
Which would capture the last name by looking for the final capitalized word.
 
Share this answer
 
Comments
Maciej Los 5-Aug-15 2:31am    
5ed!

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