What method in the String class returns only the first N characters?

后端 未结 12 984
醉话见心
醉话见心 2020-11-27 12:27

I\'d like to write an extension method to the String class so that if the input string to is longer than the provided length N, only the first

12条回答
  •  感情败类
    2020-11-27 13:03

    if we are talking about validations also why we have not checked for null string entries. Any specific reasons?

    I think below way help since IsNullOrEmpty is a system defined method and ternary operators have cyclomatic complexity = 1 while if() {} else {} has value 2.

        public static string Truncate(string input, int truncLength)
        {
            return (!String.IsNullOrEmpty(input) && input.Length >= truncLength)
                       ? input.Substring(0, truncLength)
                       : input;
        }
    

提交回复
热议问题