Reputation: 63
I have a problem with getting a certain characters in a string. For example, if a person has 2 names in his first name, I'd only like to get the first one.
First Name: Jan Edson
Output: Jan
I've been trying the Trim()
method but It only removes extra whitespaces.
I haven't tried Substring()
yet.
Are there other ways? Please help.
Thanks!
Upvotes: 2
Views: 4280
Reputation: 1728
you need to identify the space
For eg.
String Name = "sdf fsd";
FirstName = Name .Substring(0, Name.IndexOf(' '));
Upvotes: 1
Reputation: 4067
There are several ways to achieve this. One of them is using String.Split
string text = "Jan Edson";
char[] delimiterChars = { ' ', ',', '.', ':', '\t' };
string[] words = text.Split(delimiterChars);
string firstName = "";
if (words.Count > 1)
firstName = word[0];
Upvotes: 0
Reputation: 7546
using System.Text.RegularExpressions;
string firstName = Regex.Match("Jan Edson", @"\w*").ToString();
Upvotes: 3
Reputation: 5851
You should use String.Split()
and split by the whitespace character.
This will result in an array with both Jan
and Edson
// The input string
const string name = "Jan Edson";
// Split by the spacebar
var nameParts = name.Split(' ');
// Will return 'Jan'
string firstPart = nameParts[0];
Upvotes: 4