C# 取一个字符串的子串 [英] C# take a substring of a string
问题描述
仅当该文件没有特定模式时,我才从文件中取出一行..我想从该行中取出最后 3 个字符...我的代码是:
I am taking a line from a file only if that file doen't have a specific pattern.. and i want to take from that line the last 3 chars... my code is:
while (!line.Contains(pattern))
{
String num = line.Substring((line.Length - 3), (line.Length - 2));
System.Console.WriteLine(num);
}
但是我得到一个错误..
but i get an error..
索引和长度必须指向字符串中的某个位置.参数名称:长度
Index and length must refer to a location within the string. Parameter name: length
为什么我会这样?我在行尾前 3 个字符开始新字符串,然后在 .. 之前停止 2 个字符:\
why i get that? i am starting the new string 3 chars before the end of the line and i stop 2 chars before.. :\
推荐答案
Substring 接受一个偏移量,然后返回一些字符:
Substring takes an offset and then a number of characters to return:
http://msdn.microsoft.com/en-us/library/aa904308%28v=VS.71%29.aspx
所以:
String num = line.Substring((line.Length - 3), 3);
这当然假设 line.Length > 3.你可以检查:
This of course assumes that line.Length > 3. You could check with:
String num = (line.Length < 3) ? line : line.Substring((line.Length - 3), 3);
这篇关于C# 取一个字符串的子串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!