In my application I am allowing string length upto 255 characters while entering in Database.
What I need is I have a field called "Name", I am entering the value like
Name = DisplayName + "_" + UniqueName;
And I am checking the whole "Name" value is greater than 255 and if so, Need to remove that extra characters from DisplayName alone.
Something like, Name = "abcefghijklmnopqrstuvwxyz" + "_" + "zyxwvutsrqponmlkjihgfecba";
If I have string like this and if the char greater than 255, (say 270) I need to remove 15 char from display name.
How to achieve this in C# ??
The question is a little unclear to me. But if you want to remove the extra characters from Name
after setting its value you could use String.Substring
Name = DisplayName + "_" + UniqueName;
Name = Name.Length()<=255 ? Name : Name.SubString(0,254);
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:
I made an extension method to do this:
public static string RemoveExcessCharacters(this string value, int maxLen)
{
return (value.Length > maxLen) ? value.Substring(0, maxLen) : value;
}
Used like:
string value = "abcdefg".RemoveExcessCharacters(3);
Returns "abc"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With