I have read this question to get first char of the string. Is there a way to get the first n number of characters from a string in C#?
I use:
var firstFive = stringValue?.Substring(0, stringValue.Length >= 5 ? 5 : customAlias.Length);
or alternative if you want to check for Whitespace too (instead of only Null):
var firstFive = !String.IsNullOrWhiteSpace(stringValue) && stringValue.Length >= 5 ? stringValue.Substring(0, 5) : stringValue
If we want only first 5 characters from any field, then this can be achieved by Left Attribute
Vessel = f.Vessel !=null ? f.Vessel.Left(5) : ""
Use the PadRight function to prevent the string from being too short, grab what you need then trim the spaces from the end all in one statement.
strSomeString = strSomeString.PadRight(50).Substring(0,50).TrimEnd();
This is how you do it in 2020:
var s = "ABCDEFGH";
var first5 = s.AsSpan(0, 5);
A Span<T> points directly to the memory of the string, avoiding allocating a temporary string. Of course, any subsequent method asking for a string
requires a conversion:
Console.WriteLine(first5.ToString());
Though, these days many .NET
APIs allow for spans. Stick to them if possible!
Note: If targeting .NET Framework
add a reference to the System.Memory package, but don't expect the same superb performance.
Kindly try this code when str is less than 5.
string strModified = str.Substring(0,str.Length>5?5:str.Length);
Just a heads up there is a new way to do this in C# 8.0: Range operators
Microsoft Docs
Or as I like to call em, Pandas slices.
Old way:
string newString = oldstring.Substring(0, 5);
New way:
string newString = oldstring[..5];
Which at first glance appears like a pretty bad tradeoff of some readability for shorter code but the new feature gives you
cool stuff like this:
var slice1 = list[2..^3]; // list[Range.Create(2, Index.CreateFromEnd(3))]
var slice2 = list[..^3]; // list[Range.ToEnd(Index.CreateFromEnd(3))]
var slice3 = list[2..]; // list[Range.FromStart(2)]
var slice4 = list[..]; // list[Range.All]