Use of Substring

  • Thread starter Thread starter shapper
  • Start date Start date
S

shapper

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,
Miguel
 
This may not be the most concise way but this is how I do that:


Dim strSplit() as string
Dim FirstName as string
Dim LastName as string
Dim MiddleName as string

strSplit = split(name ," ")

if strSplit.count = 2 then
FirstName = strSplit(0)
LastName = strSplit(1)
elseif strSplit.count = 3 then
FirstName = strSplit(0)
MiddleName = strSplit(1)
LastName = strSplit(2)
end if

HTH,
Ron
 
Miguel,

This is how I do it:

Dim myName As String = "John Smith Curtis"
Dim myFirstName As String = Left(myName, InStr(myName, " "))



myFirstName should = "John"

I'm using the instring function to locate the numeric value location of
the first space and then using it in a Left function to get the first
name.

Hope this helps,

Luis Miguel Rodrigues
 
When you say you want to remove the first word, do you mean you want myName
to equal "Smith Curtis"? If that's the case, then you'd have to reassign
the results of SubString, since Strings are immutable (you can reassign but
not change the contents of the memory it is referencing).

So you've got:
String myName = "John Smith Curtis";

System.Diagnostics.Debug.WriteLine(myName.Substring(0, myName.IndexOf("
")));

System.Diagnostics.Debug.WriteLine(myName.Substring(myName.IndexOf(" ") +
1)); // Warning: this would break if myName == "John " or has no spaces but
for your sample, it works
 
Back
Top