Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove characters in string when it reaches specific length

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# ??

like image 577
Shesha Avatar asked Jan 11 '16 04:01

Shesha


3 Answers

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);
like image 85
Alex Jolig Avatar answered Oct 26 '22 09:10

Alex Jolig


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:

  1. Variables/constants/configuration to specify the maximum length and maybe the delimiter character as well.
  2. Error checking to make sure Split() returns exactly two parts, for instance.
like image 40
Avner Shahar-Kashtan Avatar answered Oct 26 '22 08:10

Avner Shahar-Kashtan


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"

like image 2
duck Avatar answered Oct 26 '22 09:10

duck