我是c#的新手,我有一点问题。我有string
:
string file = "Eep_A5000400A_A4000500A$1000219_Mura_20190409003057.eep";
string name1;
string name2;
string name3;
string name4;
如何获得string
的位置
6..12 -> "5000400"
16..22 -> "4000500"
33..36 -> "Mura"
53..55 -> "eep"
通过使用IndexOf
或Substring
? (上面的file
只是一个例子,里面的string
可能会有所不同)。举个例子,我的期望结果是:
Console.WriteLine(name1);
Console.WriteLine(name2);
Console.WriteLine(name3);
Console.WriteLine(name4);
结果:
5000400
4000500
Mura
eep
你们有什么想法吗?提前致谢。
简单的算术应该做:
string name = file.Substring(startIndex - 1, stopIndex - startIndex + 1);
在你的情况下
name1 = file.Substring( 6 - 1, 12 - 6 + 1);
name2 = file.Substring(16 - 1, 22 - 16 + 1);
name3 = file.Substring(33 - 1, 36 - 33 + 1);
name4 = file.Substring(53 - 1, 55 - 53 + 1);
您可能希望为此实现扩展方法:
public static partial class StringExtensions {
public static string FromTo(this string value, int fromIndex, int toIndex) {
if (null == value)
throw new ArgumentNullException(nameof(value));
else if (fromIndex < 1 || fromIndex > value.Length)
throw new ArgumentOutOfRangeException(nameof(fromIndex));
else if (toIndex < 1 || toIndex > value.Length || toIndex < fromIndex)
throw new ArgumentOutOfRangeException(nameof(toIndex));
return value.Substring(fromIndex - 1, toIndex - fromIndex + 1);
}
}
然后就这么简单
name1 = file.FromTo( 6, 12);
name2 = file.FromTo(16, 22);
name3 = file.FromTo(33, 36);
name4 = file.FromTo(53, 55);
C#String.Substring方法在C#和.NET中,字符串由String类表示。 String.Substring方法从C#中的字符串实例检索子字符串。该方法具有以下两种重载形式。
因此,在您的情况下,您可以使用以下内容:
string file = "Eep_A5000400A_A4000500A$1000219_Mura_20190409003057.eep";
string name1 = file.Substring(6, 7); //6..12 -> "5000400"
string name2 = file.Substring(16, 7); //16..22 -> "4000500"
string name3 = file.Substring(33, 4); //33..36 -> "Mura"
string name4 = file.Substring(53, 2); //53..55 -> "eep"