Wednesday, March 28, 2012

Substring

Hello

I have the following string:

myName = "John Smith Curtis"

I want to get the first word, i.e. "John", which means I want to get everything from the start to the first space.

I know I should use Substring but I don't know what to do to remove the first word.

Thanks,
Miguelstring myName = "John Smith Curtis";
myName = myName.Substring( 0, myName.IndexOf( " " ) );

The best way to go though would be to do

myName.Split(" ")(0) -> That will return the first element before the space

If you really want to us substring then do

myName.Substring(0,4)


myName.Remove(myName.IndexOf(' ')) will return "John"


try the following ( i didnt check for going out of bound to keep the example simple)

string myName = "John Smith Curtis";

//get the index of the frist space
int index = myName.IndexOf(" ");

//get the first word
string firstname = myName.Substring(0, index);

//remove the first word
myName = myName.Remove(0, index + 1);

0 comments:

Post a Comment