我正在尝试找出获取字符串中 - 字符之前所有内容的最佳方法。下面是一些示例字符串。 - 之前的字符串长度各不相同,可以是任意长度
223232-1.jpg
443-2.jpg
34443553-5.jpg
所以我需要从起始索引 0 到 - 之前的值。所以子字符串会变成 223232、443 和 34443553
最佳答案
class Program
{
static void Main(string[] args)
{
Console.WriteLine("223232-1.jpg".GetUntilOrEmpty());
Console.WriteLine("443-2.jpg".GetUntilOrEmpty());
Console.WriteLine("34443553-5.jpg".GetUntilOrEmpty());
Console.ReadKey();
}
}
static class Helper
{
public static string GetUntilOrEmpty(this string text, string stopAt = "-")
{
if (!String.IsNullOrWhiteSpace(text))
{
int charLocation = text.IndexOf(stopAt, StringComparison.Ordinal);
if (charLocation > 0)
{
return text.Substring(0, charLocation);
}
}
return String.Empty;
}
}
结果:
223232
443
34443553
344
34
关于c# - 获取子字符串 - 特定字符之前的所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1857513/