How to break on string into two seperate variable or strings in C#

  • Thread starter Thread starter Brad Britton
  • Start date Start date
B

Brad Britton

Just wondering how you would break a string such as first and last name
together, into two separate strings or variables, each containing the
firstName and lastName. I am a newbie at C# so any help would be great!

Thanks

Brad
 
[Removed microsoft.public.dotnet.csharp.general which isn't a valid
newsgroup, and comp.programming as I'm not sure whether it's on-topic
there.]

Brad Britton said:
Just wondering how you would break a string such as first and last name
together, into two separate strings or variables, each containing the
firstName and lastName. I am a newbie at C# so any help would be great!

Have a look at String.Substring, String.IndexOf and String.Split.
 
You can use the Split method of the String class.
Sample:
String sName = "Name1 Name2";
String[] sResult = sName.Split(' ');


Sacalul
 
In addition remember that you can split from more separators...
String[] sResult = sName.Split( ' ', ';', ',' '\' ); // and so on
 
Here's one way:

string fullName = "your name";
string[] firstAndLast = fullName.Split(new char[] { ' ' });

// results:
// firstAndLast[0] == "your";
// firstAndLast[1] == "name";
--------------------
Content-Class: urn:content-classes:message
From: "rb" <[email protected]>
Sender: "rb" <[email protected]>
References: <N5%[email protected]>
Subject: How to break on string into two seperate variable or strings in C#
Date: Wed, 30 Jul 2003 19:46:04 -0700
Lines: 16
Message-ID: <[email protected]>
MIME-Version: 1.0
Content-Type: text/plain;
charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
X-Newsreader: Microsoft CDO for Windows 2000
Thread-Index: AcNXDeJq/ooy42iUSVawb2gRjNMrZA==
X-MimeOLE: Produced By Microsoft MimeOLE V5.50.4910.0300
Newsgroups: microsoft.public.dotnet.languages.csharp
Path: cpmsftngxa06.phx.gbl
Xref: cpmsftngxa06.phx.gbl microsoft.public.dotnet.languages.csharp:173141
NNTP-Posting-Host: TK2MSFTNGXA11 10.40.1.163
X-Tomcat-NG: microsoft.public.dotnet.languages.csharp

FA Q


--

This posting is provided "AS IS" with no warranties, and confers no rights.
Use of included script samples are subject to the terms specified at
http://www.microsoft.com/info/cpyright.htm

Note: For the benefit of the community-at-large, all responses to this
message are best directed to the newsgroup/thread from which they
originated.
 
Back
Top