1

I have the following strings:

var temp = null;
var temp = "";
var temp = "12345678";
var temp = "1234567890";

What I need to do is if have a function that will give me the last four digits of the input variable if the input variable is 8 or 10 characters long. Otherwise I need it to return "";

Is there an easy way I can do this in C#. I am just not sure how to deal with null because if I get the length of null then I think that will give me an error.

0

4 Answers 4

2
int length = (temp ?? "").Length;
string subString = "";
if(length == 8 || length == 10)
{
   subString = temp.Substring(length - 4);
}
Sign up to request clarification or add additional context in comments.

Comments

2

You can use IsNullOrEmpty, As if string is null or Empty then substring is not possible.

if (!String.IsNullOrEmpty(str) && (str.Length == 8 || str.Length == 10)) 
{
    string substr = str.Substring(str.Length-4);
}

Comments

1

Try this

string YourFunctionName(string input)
    {
        string rVal = "";
        if (string.IsNullOrEmpty(input))
            return rVal;
        if (input.Length == 8 || input.Length == 10)
            rVal = input.Substring(input.Length - 4);
        return rVal;
    }

Comments

0

I would likely write it like this, if writing a function:

string GiveMeABetterName (string input) {
    if (input != null
          && (input.Length == 8 || input.Length == 10)) {
        return input.Substring(input.Length - 4);
    } else {
        return "";
    }
}

As can be seen by all the answers, there is multiple ways to accomplish this.

Comments

Your Answer

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