patterncsharpMinor
String Extension improvement
Viewed 0 times
improvementstringextension
Problem
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?
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 ();
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;
}Solution
You should remove this
because length already includes the spaces.
This
should be
because
Also: why
You can also do it in a single loop like this:
length = length + namelist.Count() - 1;because length already includes the spaces.
This
length = length - namelist[i].Length;should be
length -= namelist[i].Length - 1;because
namelist[i].Length-1 is the number of characters that are removed.Also: why
i >=1 - 1 instead of i >= 0?You can also do it in a single loop like this:
for (var i = namelist.Count() - 2; i >=1 && length > 20; i--)
{
length -= namelist[i].Length - 1;
namelist[i] = namelist[i].Substring(0, 1);
}
return string.Join(" ", namelist);Code Snippets
length = length + namelist.Count() - 1;length = length - namelist[i].Length;length -= namelist[i].Length - 1;for (var i = namelist.Count() - 2; i >=1 && length > 20; i--)
{
length -= namelist[i].Length - 1;
namelist[i] = namelist[i].Substring(0, 1);
}
return string.Join(" ", namelist);Context
StackExchange Code Review Q#37121, answer score: 2
Revisions (0)
No revisions yet.