C# 如果长度大于 String 的长度,则子字符串无法按预期工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11032394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Substring not working as expected if length greater than length of String
提问by Lordlebu
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.
捕获值的前 40 个字符。
If the value at Ais more than 40, Bis able to capture, but if the value of Ais less than 40, there is no value being captured at B.
如果 at 的值A大于40,B则可以捕获,但如果 的值A小于40,则在 处没有值被捕获B。
采纳答案by Ankita Sen
String.Concat does not serve your purpose here. You should rather do the following:
String.Concat 在这里不能满足您的目的。您应该执行以下操作:
if(A.Length > 40)
B= A.Substring(0,40);
else
B=A;
回答by Me.Name
Quick and dirty:
又快又脏:
A.Length > 40 ? A.Substring(0, 40) : A
回答by sloth
回答by Chris Gessler
Why not 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:
在您的 StringTool 类中:
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);
回答by Philip
use below code to substring
使用下面的代码来子串
B = String.padright(40).Substring(0, 40))
回答by Jacob Sobus
Extensions are best for problems like this one ;) Mine have some dirty name but everyone know what it would do - this is exception safe substring:
扩展最适合解决这样的问题 ;) 我的名字有些脏,但每个人都知道它会做什么 - 这是异常安全的子字符串:
public static string SubstringNoLongerThanSource(this string source, int startIndex, int maxLength)
{
return source.Substring(startIndex, Math.Min(source.Length - startIndex, maxLength));
}
回答by irfandar
B = string.Concat(A.Substring(0, Math.Min(40, A.Length)));

