Assuming DisplayName
and UniqueName
are assured to not contain your delimiter character "_", you will have to split the string, modify (what used to be) DisplayName and reconcat them:
var displayName = "Shesha";
var uniqueName = "555";
var fullName = displayName + "_" + uniqueName;
if (fullName.Length > 255)
{
var charsToRemove = fullName.Length - 255;
// split on underscore.
var nameParts = fullName.Split('_');
var displayNameLength = nameParts[0].Length;
var truncatedDisplayName = nameParts[0].Substring(0, displayNameLength - charsToRemove);
fullName = truncatedDisplayName + "_" + nameParts[1];
}
Of course, all this assumes that this length check occurs after the full name has been constructed. You can of course do the check before, saving yourself the effort of splitting:
var combinedLength = displayName.Length + uniqueName.Length + 1; // 1 for _.
var charsToRemove = combinedLength - 255;
if (charsToRemove > 0)
{
// same logic as above, but instead of splitting the string, you have
// the original parts already.
}
And of course, this is just a basic example. Real code should also have:
- Variables/constants/configuration to specify the maximum length and maybe the delimiter character as well.
- Error checking to make sure Split() returns exactly two parts, for instance.