Substring not working as expected if length greater than length of String
Solution 1
String.Concat does not serve your purpose here. You should rather do the following:
if(A.Length > 40)
B = A.Substring(0, 40);
else
B = A;
Solution 2
Quick and dirty:
A.Length > 40 ? A.Substring(0, 40) : A
Solution 3
Create an extension for it... Call it Truncate or Left, or whatever.
public static class MyExtensions
{
public static string Truncate(this string s, int length)
{
if(s.Length > length)
return s.Substring(0, length);
return s;
}
}
Then you can simply call it like so:
string B = A.Truncate(40);
Also note that you don't have to make it an extension method, although it would be cleaner.
In your StringTool class:
public static string Truncate(string value, int length)
{
if(value.Length > length)
return value.Substring(0, length);
return value;
}
And to call it:
string B = StringTool.Truncate(A, 40);
Solution 4
Use the below code to substring.
B = String.padright(40).Substring(0, 40)).Trim()
Solution 5
Extensions are best for problems like this one ;)
Mine have some dirty name, but everyone knows what it would do - this is an exception-safe substring:
public static string SubstringNoLongerThanSource(this string source, int startIndex, int maxLength)
{
return source.Substring(startIndex, Math.Min(source.Length - startIndex, maxLength));
}
Related videos on Youtube
Lordlebu
Updated on February 18, 2021Comments
-
Lordlebu about 3 years
Ok guys, I know if/else works, i needed an alternative.
I am using
B = String.Concat(A.Substring(0, 40));
to capture the first 40 characters of a value.
If the value at
A
is more than40
,B
is able to capture, but if the value ofA
is less than40
, there is no value being captured atB
.-
Rawling almost 12 yearsWhy are you calling
String.Concat
with a single input? -
DaveShaw almost 12 yearsWhat is the purpose of
String.Concat()
? Ypu normally use it to join two strings together, but you are only passing in one String? -
CodeCaster almost 12 years"but if the [length of the] value of A is less than 40, there is no value being captured at B." - probably because an exception occurred.
-
Christian.K almost 12 yearsThere is no value "being" captured, because in that case
Substring
will throw anArgumentOutOfRangeException
(message "Index and length must refer to a location within the string."). More code/context is required to judge further. -
Joanna Derks almost 12 yearswhat are you trying to achieve? it seems that whatever it is you are doing it the wrong way...
-
sloth almost 12 yearspossible duplicate of C# take a substring of a string
-
-
ean5533 almost 12 yearsSimilar quick and dirty:
A.Substring(0, Math.Min(40, A.Length))
-
Paolo Tedesco almost 12 yearsQuick for sure, but why should it be dirty :) ?
-
Me.Name almost 12 years@benjer: I know that feeling, stackoverflow is the busiest forum on the web :)
-
Me.Name almost 12 years@PaoloTedesco , perhaps not dirty, but had to put down something :p
-
Me.Name almost 12 years@ean5533 : that was my first impulse as well, but that would cause a possible unnecessary call to substring (yeah I know, micromanagement talk :D )
-
SimpleVar almost 12 years@Me.Name Oh yeah, that moment when you know you must put "and something" afterwards... Precious times, I tell you... That's life. It's the little things, really... "Quick and dirty", ugh, that is brilliant... Little things...
-
Lordlebu almost 12 yearstruncate would be the right fix, there is already a very huge number of if/elses in the code.
-
Security Hound almost 12 years@Lordlebu - Why are you trying to reduce the number of if/else statements exactly?
-
Lordlebu almost 12 yearsok one error - emlMessage.cs(198,35): error CS0117: 'string' does not contain a definition for 'Truncate', I tried StringTool, still doesnot work
-
Lordlebu almost 12 yearsnot working emlMessage.cs(198,9): error CS0201: Only assignment, call, increment, decrement, and new object expressions can be used as a statement. Actually the database has 40 length.
-
Chris Gessler almost 12 yearserr... probably needs to be static.
-
sloth almost 12 years@Ramhound In which way exactly will this fail? Did you even test it? I don't think you know what
Left
does. -
Me.Name almost 12 yearsWhat is the complete code? To be used it must be assigned to a variable (or result) as in : B = A.Length > 40 ? A.Substring(0, 40) : A;
-
Ry- almost 12 yearsUsing
Left
is even considered bad practice in VB.NET, let alone importing the VB-legacy namespace into C# to use it there... -
Security Hound almost 12 years@dkson - Fine. I took ANOTHER look at the method. If length is longer then the length of the string the entire string is returned. I still maintain this is bad practice and thus a bad answer so going to maintain my down vote.
-
sloth almost 12 years@Ramhound Fine. You took another look at the method. If length is longer then the length of the string the entire string is returned. Otherwise, the string is truncated to the given length. That's exactly what the questioner asked for, and that's what the accepted answer does. So basically you are saying it is bad practice to use a well-tested, well-known and well-documented method of the .Net framework and you should instead reinvent the wheel and write a method that does the exact same thing.
-
Admin almost 12 years@minitech Why should this be bad practice? So you're not allowed to use methods in C# if there's 'VisualBasic' in the namespace? What's the problem?
-
Ry- almost 12 years@user1443957: It's not specific to C#; I wouldn't use those methods in VB.NET, either. They're leftovers from VB6 and they look ugly and you shouldn't use them. It's akin to still checking for and using
document.all
in JavaScript, if that happens to be your area of expertise. -
N_A over 10 years@ean5533 Best "answer". Most clearly expresses intent.
-
ruffin over 10 yearsThough make ean5533's an extension method, and we're lots closer to Step 3, Profit.
-
Kevin Cloet over 9 yearsLove this solution actually
-
Gh61 over 8 yearsBut after the text there are many spaces. You should use this:
B = String.padright(40, '\0').Substring(0, 40))
-
Brain2000 about 8 yearsThere's nothing wrong with using Left( ). If it bothers you, make a string extension called Left( ).
-
jolySoft over 7 yearsSimple and elegant, plus can be used inline without additional method
-
Nigel Fds over 6 years@ean5533 solution is better and simple .. A.Substring(0, Math.Min(40, A.Length))
-
Jacob Sobus over 5 yearsExtension method is already there on my answer stackoverflow.com/a/30692581/1696967 :)
-
voxoid about 5 yearsYes! I prefer Math.Min() over a ternary expression or if/else; keeps the check within the space of the parameter, rather than cluttering things outside of it.
-
stomy almost 5 yearsTrim the result to get rid of extra spaces.
"1234".PadRight(40).Substring(0, 40).TrimEnd()
-
Triynko about 3 yearsThis performs unnecessary string allocations, by first creating a string with more spaces, and then trimming those spaces off. It's more efficient to just perform the length check up front.
-
Peter Mortensen almost 2 yearsCan you explain your answer, please? E.g., it could include references to the ternary operator. And what the disadvantage is. (But without "Edit:", "Update:", or similar - the answer should appear as if it was written today.)
-
Peter Mortensen almost 2 yearsWhat makes it exception-safe? Is it in contrast to some other answers?
-
Peter Mortensen almost 2 yearsCan you link to documentation (non-naked link)?
-
Jacob Sobus almost 2 years@PeterMortensen Because this method is checking if end index is not bigger than string length so no ArgumentOutOfRangeException will be thrown