Teo*_*gul 27
string s = "Lots and lots of characters";
string firstTen = s.Substring(0, 10);
Run Code Online (Sandbox Code Playgroud)
Tom*_*Tom 11
您可以创建一个扩展方法,如下所示:
public static class Extension
{
public static string Left(this String input, int length)
{
return (input.Length < length) ? input : input.Substring(0, length);
}
}
Run Code Online (Sandbox Code Playgroud)
然后像这样调用它:
string something = "I am a string... truncate me!";
something.Left(10);
Run Code Online (Sandbox Code Playgroud)
一种快速的单行代码,其中变量s
是您的字符串:
public string GetFirstTenCharacters(string s)
{
// This says "If string s is less than 10 characters, return s.
// Otherwise, return the first 10 characters of s."
return (s.Length < 10) ? s : s.Substring(0, 10);
}
Run Code Online (Sandbox Code Playgroud)
只需像这样调用这个方法:
string result = this.GetFirstTenCharacters("Hello, this is a string!");
Run Code Online (Sandbox Code Playgroud)
依靠 :-)
\n\n通常你可能正在寻找 SubString...但是如果你正在使用 unicode 做一些奇特的事情,这演示了哪里会出错(例如 unicode 范围 > 0xFFFF):
\n\nstatic void Main(string[] arg)\n{\n string ch = "(\\xd808\\xdd00\xe6\xb1\x89\xe8\xaf\xad or \xe6\xbc\xa2\xe8\xaa\x9e, H\xc3\xa0ny\xc7\x94)";\n\n Console.WriteLine(ch.Substring(0, Math.Min(ch.Length, 10)));\n\n var enc = Encoding.UTF32.GetBytes(ch);\n string first10chars = Encoding.UTF32.GetString(enc, 0, Math.Min(enc.Length, 4 * 10));\n Console.WriteLine(first10chars);\n\n Console.ReadLine();\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n出错的原因是因为字符是 16 位,并且长度检查 UTF-16 字符而不是 unicode 字符。也就是说,这可能不是您的情况。
\n 归档时间: |
|
查看次数: |
55956 次 |
最近记录: |