获取子串 - 在某些char之前的所有内容

Pos*_*Guy 109 c#

我试图弄清楚在字符串中的字符之前获取所有内容的最佳方法.下面是一些示例字符串.之前字符串的长度 - 变化,可以是任何长度

223232-1.jpg
443-2.jpg
34443553-5.jpg
Run Code Online (Sandbox Code Playgroud)

所以我需要从起始索引0到右前的值 - .所以子串会变成223232,443和34443553

Fre*_*dou 123

.Net小提琴的例子

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果你想要一个单线程而不会丢失正确的"未找到"检查,那么你可以这样做:`string result = source.Substring(0,Math.Max(source.IndexOf(' - '),0))` (14认同)
  • 请帮他们一个忙,并添加错误检查,假设他计划用这个来制作一个函数:) (2认同)
  • 当s(已知)(如此处)知道字符串`s`的长度严格超过`n`时,可以使用`s.Substring(0,n)`而不是`s.Substring(0,n)`. (2认同)

Dom*_*nin 107

使用拆分功能.

static void Main(string[] args)
{
    string s = "223232-1.jpg";
    Console.WriteLine(s.Split('-')[0]);
    s = "443-2.jpg";
    Console.WriteLine(s.Split('-')[0]);
    s = "34443553-5.jpg";
    Console.WriteLine(s.Split('-')[0]);

Console.ReadKey();
}
Run Code Online (Sandbox Code Playgroud)

如果你的字符串没有,-那么你将得到整个字符串.

  • 几年后,我才刚刚意识到我很快就承认詹姆斯的观点了.该问题询问如何在某个字符之前找到该字符串.因此,该角色的进一步实例是无关紧要的,并且[0]将"正常工作".当然,它仍取决于我们对输入数据的信任程度.如果根本没有" - "怎么办? (6认同)
  • 如果你有多个连字符,你的数组中会有多个元素. (4认同)
  • 确实,詹姆斯,所以如果你只想要一个连字符,这只会是一个解决方案.我想你可以使用像skip和aggregate这样的Linq方法来获得你想要的东西,但是你已经获得了比已经提出的方法更多的代码.这完全取决于您对传入数据的了解程度. (2认同)
  • 我不会担心“不必要的垃圾”。以这种方式创建的任何额外字符串将立即无法访问,因此会在第 0 代中收集,这确实是一个非常低的开销。垃圾收集器的设计明确旨在允许使用大量的短期项目而几乎不花钱。 (2认同)

Bra*_*ore 63

String str = "223232-1.jpg"
int index = str.IndexOf('-');
if(index > 0) {
    return str.Substring(0, index)
}
Run Code Online (Sandbox Code Playgroud)

  • 这实际上与Fredou给出的答案相同(目前是最佳答案),但它忽略了处理未找到匹配的情况. (2认同)

Dar*_*iak 8

稍微修改和刷新了 Fredou 针对 C# \xe2\x89\xa5 8 的解决方案

\n\n
/// <summary>\n/// Get substring until first occurrence of given character has been found. Returns the whole string if character has not been found.\n/// </summary>\npublic static string GetUntil(this string that, char @char)\n{\n    return that[..(IndexOf() == -1 ? that.Length : IndexOf())];\n    int IndexOf() => that.IndexOf(@char);\n}\n
Run Code Online (Sandbox Code Playgroud)\n

测试:

\n
[TestCase("", \' \', ExpectedResult = "")]\n[TestCase("a", \'a\', ExpectedResult = "")]\n[TestCase("a", \' \', ExpectedResult = "a")]\n[TestCase(" ", \' \', ExpectedResult = "")]\n[TestCase("/", \'/\', ExpectedResult = "")]\n[TestCase("223232-1.jpg", \'-\', ExpectedResult = "223232")]\n[TestCase("443-2.jpg", \'-\', ExpectedResult = "443")]\n[TestCase("34443553-5.jpg", \'-\', ExpectedResult = "34443553")]\n[TestCase("34443553-5-6.jpg", \'-\', ExpectedResult = "34443553")]\npublic string GetUntil(string input, char until) => input.GetUntil(until);\n
Run Code Online (Sandbox Code Playgroud)\n


Ant*_*ser 6

自从该线程启动以来,情况有所发展。

现在,您可以使用

string.Concat(s.TakeWhile((c) => c != '-'));
Run Code Online (Sandbox Code Playgroud)


Mic*_*tta 5

一种方法是与String.Substring一起使用String.IndexOf

int index = str.IndexOf('-');
string sub;
if (index >= 0)
{
    sub = str.Substring(0, index);
}
else
{
    sub = ... // handle strings without the dash
}
Run Code Online (Sandbox Code Playgroud)

从位置 0 开始,返回直到破折号(但不包括破折号)的所有文本。

  • @NRNR:如果你这么说。OP 了解业务需求,而不是您或我。 (5认同)