Remove characters in string when it reaches specific length

Shesha picture Shesha · Jan 11, 2016 · Viewed 7.1k times · Source

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

Answer

Alex Jolig picture Alex Jolig · Jan 11, 2016

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);