ADO DOT NET Posted December 12, 2007 Posted December 12, 2007 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? Quote
Administrators PlausiblyDamp Posted December 12, 2007 Administrators Posted December 12, 2007 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... Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
Leaders snarfblam Posted December 15, 2007 Leaders Posted December 15, 2007 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. Quote [sIGPIC]e[/sIGPIC]
JumpyNET Posted December 19, 2007 Posted December 19, 2007 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) Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.