I am creating a string extension to validate some input.
My scenario is when we have a string it will format it according to following guideline. If the sample string is “One Two Three Four Five” and the length is <=20 return same. If more than 20 then “One Two Three F Five”. If still length is more than 20 the “One Two T F Five” etc...
Is there any way I can improve this code? I thought it can use recursion?
public static string ToShortName(this string name)
{
if (name.Length <= 20) return name;
var namelist = name.Split(' ');
var length = name.Length;
//add spaces
length = length + namelist.Count() - 1;
var output = "";
var indexList = new List<int>();
for (var i = namelist.Count() - 2; i >=1 ; i--)
{
indexList.Add(i);
if (length - namelist[i].Length <= 20)
{
break;
}
length = length - namelist[i].Length;
}
foreach (var i in indexList)
{
namelist[i] = namelist[i].Substring(0, 1);
}
output = string.Join(" ", namelist);
return output;
}
result>20
. (I believe no one will have name initial which can occupy 20 characters though:)) \$\endgroup\$