3

Just curious if I can substring string only when String.Length is greater than or equal to 20 without using If or Try catch ?

Thanks!

6 Answers 6

19

Ummh what have you tried? Just check beforehand:

if(input.Length >= 20)
{
   input = input.Substring(0,20);
}

If you really don't want to use an if statement you could use Linq which just obfuscates the solution though and is less performant in this case:

input = new string(input.Take(20).ToArray());

Or technically this doesn't use an if statement either:

input = input.Length >= 20 ? input.Substring(0,20) : input;
Sign up to request clarification or add additional context in comments.

Comments

13

Use a string extension. It still uses an IF, however, it makes your code cleaner when using it.

    public static string Left(this string input, int length)
    {
        string result = input;
        if (input != null && input.Length > length)
        {
            result = input.Substring(0, length);
        }
        return result;
    }

usage:

input = input.Left(20);

Comments

8
someString = someString.Substring(0,Math.Min(20,someString.Length));

2 Comments

can you read question again? I am wondering I can achieve without using if or try catch???
Nice! I like this one!
2

just out of mind ...

a.SubString(Math.Min(startPos, a.Length), Math.Min(a.Length - Math.Min(startPos, a.Length),  
            requestedLen - Math.Min(startPos, a.Length);

oh my god, my brain burns, time to hit the sack...

Comments

1

This really needs clarification, as you don't state what it is you want to happen if it's less than 20. Return the original string or return null?

Anyhow, you can use a ternary operator if you don't want a if block:

(someString.Length < 20) ? someString : someString.SubString(...

Comments

0

There's no need for a try-catch if you ensure that the substring range is within the original string range. Of course, you cannot get a substring that is longer than the original one.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.