locked
Substring Not Working for Me RRS feed

  • Question

  • I have a string which comes in from the users. Sometimes it's blank, sometimes it's 10 characters, sometimes it's 50 characters, etc... it could be any length up to 255 which is allowed in the form they fill out. But the database I have to write this to restricts the length to be only 30 characters. So I think cool, I just use this:

    theString.Substring(0, 30)
    And this works great as long as the string is at least 30 characters long. So what would one do if the string comes in as only 20 characters. I could easily check that the length of theString is at least 30 before trying to work with it,  but that seems like a waste, I guess I'm spoiled on the old VB LEFT function. I have seen posts where people actually build a new method called LEFT and that works but again, it seems like a waste of code to me.

    Thursday, June 4, 2015 2:03 PM

Answers

  • You should check if the length of the string is greater than 30 before calling the Substring method:

          string theString = "...";
    
          if(theString.Length > 30)
            theString = theString.Substring(0, 30);


    This is not a waste but a perfectly fine approach here :) There is no built-in Substring method that does this for you so its either this or writing your method.

    Hope that helps.

    Please remember to close your threads by marking helpful posts as answer and then start a new thread if you have a new question. Please don't ask several questions in the same thread.


    Thursday, June 4, 2015 2:11 PM

All replies

  • You should check if the length of the string is greater than 30 before calling the Substring method:

          string theString = "...";
    
          if(theString.Length > 30)
            theString = theString.Substring(0, 30);


    This is not a waste but a perfectly fine approach here :) There is no built-in Substring method that does this for you so its either this or writing your method.

    Hope that helps.

    Please remember to close your threads by marking helpful posts as answer and then start a new thread if you have a new question. Please don't ask several questions in the same thread.


    Thursday, June 4, 2015 2:11 PM
  • Thanks. That's exactly what I did, I was just hoping there was a way to do it without the if.
    Thursday, June 4, 2015 2:15 PM