Index Out of Range

ADO DOT NET

Centurion
Joined
Dec 20, 2006
Messages
160
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:
Visual Basic:
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?
 
Just tried it here and it worked fine - what is the contents of the variable Input when you are getting the error?

If the string doesn't contain a space it will probably fail...
 
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...
Visual Basic:
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.
Visual Basic:
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.
 
Split()

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

Code:
        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)
 
Back
Top