Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

Hi,

I want to convert the FIRST WORD of my sentence to upper case.

For example:

this is a test string.

Should become:

THIS is a test string.

So I wrote this:

Input.Substring(0, Input.IndexOf(" ")).ToUpper + Input.Substring(Input.IndexOf(" "), Input.Length - Input.IndexOf(" "))

But it returns Index Out of Range ! :confused:

Anything is wrong with me?

  • Leaders
Posted

If there is no space in the string, the code will certainly fail. I think you are cramming too much logic into one line, which makes it hard to consider all of the possibilities. If you break it up...

Dim FirstSpace As Integer
Dim FirstWord As String
Dim RestOfText As String

FirstSpace = Input.IndexOf(" ")
FirstWord = Input.Substring(0, FirstSpace)
RestOfText = Input.Substring(FirstSpace, Input.Length - FirstSpace)

Dim Result As String = FirstWord.ToUpper() & RestOfText

...potential errors become more obvious. FirstSpace could have a value of -1 if there are no spaces, and that will cause an error when passed to the Substring function. Now we can easily add code to deal with the possibility of no spaces.

Dim FirstSpace As Integer
Dim FirstWord As String
Dim RestOfText As String

FirstSpace = Input.IndexOf(" ")
If FirstSpace = -1 Then ' Special case!
   'If there are no spaces then the whole string is the first word
   FirstWord = Input
   RestOfText = ""
Else
   FirstWord = Input.Substring(0, FirstSpace)
   RestOfText = Input.Substring(FirstSpace, Input.Length - FirstSpace)
End If

Dim Result As String = FirstWord.ToUpper() & RestOfText

I'm not trying to hand you the answer (this forum typically prefers to guide you in the right direction), but make the point that it is important for your code to clearly demonstrate logic.

[sIGPIC]e[/sIGPIC]
Posted

Split()

 

I don't know if you know the split function. Anyway that's one way to do it.

 

       Dim Input As String = "Word1 word2 thirdword"
       Dim Words() As String = Split(Input, " ")
       Dim Output As String = ""
       Output = UCase(Words(0))
       Dim i As Integer
       For i = 1 To Words.Length - 1
           Output = Output & " " & Words(i)
       Next
       MsgBox(Output)

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...