c# - 获取子字符串 - 特定字符之前的所有内容

标签 c# string substring

我正在尝试找出获取字符串中 - 字符之前所有内容的最佳方法。下面是一些示例字符串。 - 之前的字符串长度各不相同,可以是任意长度

223232-1.jpg
443-2.jpg
34443553-5.jpg

所以我需要从起始索引 0 到 - 之前的值。所以子字符串会变成 223232、443 和 34443553

最佳答案

.Net Fiddle example

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/

相关文章:

c# - 类似于 SQL Server Management Studio 的 WinForms DataGridView 行为

c# - 重定向命令提示符的输出

java - 从字符串中删除时间戳

Python循环遍历CSS文件中的所有url并替换

c# - 如何在另一个文本字段中查看一个文本字段中的文本?

c# - 如何通过 WCF 公开实体的计算数据

java - 当条件设置为 false 时,While 循环执行最后一次

java - 类似于 split() 的东西?

c - 如何访问嵌套结构中的指针

python - 查看列中的值是否包含 Pandas 数据框中的 %