获取 Substring-某个 char 之前的所有内容

我试图找到一个最好的方法来获得字符串中-字符前面的所有内容。下面是一些示例字符串。前面的字符串的长度可以变化,并且可以是任意长度

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

所以我需要从开始索引0到右前面-的值。所以子字符串是223232,443和34443553

374279 次浏览

. Net Fiddle 示例

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
String str = "223232-1.jpg"
int index = str.IndexOf('-');
if(index > 0) {
return str.Substring(0, index)
}

一种方法是将 String.SubstringString.IndexOf一起使用:

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

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

使用 分开函数。

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();
}

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

自从这个帖子开始以来,事情有了一些进展。

现在,你可以用

string.Concat(s.TakeWhile((c) => c != '-'));

基于 BrainCore 的回答:

    int index = 0;
str = "223232-1.jpg";


//Assuming we trust str isn't null
if (str.Contains('-') == "true")
{
int index = str.IndexOf('-');
}


if(index > 0) {
return str.Substring(0, index);
}
else {
return str;
}

可以为此使用正则表达式,但是当输入字符串与正则表达式不匹配时,最好避免额外的异常。

首先,为了避免转义为 regex 模式带来的额外麻烦,我们可以直接使用 function:

String reStrEnding = Regex.Escape("-");

我知道这不会做任何事情-因为“-”与 Regex.Escape("=") == "="相同,但是如果字符是 @"\",它会有所不同。

然后我们需要匹配从乞求字符串到字符串结束,或者交替如果结束没有找到-然后不匹配任何东西。(空弦)

Regex re = new Regex("^(.*?)" + reStrEnding);

如果您的应用程序是性能关键的-那么新的正则表达式的单独行,如果不是-您可以将所有内容放在一行中。

最后对字符串进行匹配并提取匹配的模式:

String matched = re.Match(str).Groups[1].ToString();

然后你可以写一个单独的函数,就像在另一个答案中一样,或者写一个内联的 lambda 函数。我现在使用了两种表示法——内联 lambda 函数(不允许默认参数)或单独的函数调用。

using System;
using System.Text.RegularExpressions;


static class Helper
{
public static string GetUntilOrEmpty(this string text, string stopAt = "-")
{
return new Regex("^(.*?)" + Regex.Escape(stopAt)).Match(text).Groups[1].Value;
}
}


class Program
{
static void Main(string[] args)
{
Regex re = new Regex("^(.*?)-");
Func<String, String> untilSlash = (s) => { return re.Match(s).Groups[1].ToString(); };


Console.WriteLine(untilSlash("223232-1.jpg"));
Console.WriteLine(untilSlash("443-2.jpg"));
Console.WriteLine(untilSlash("34443553-5.jpg"));
Console.WriteLine(untilSlash("noEnding(will result in empty string)"));
Console.WriteLine(untilSlash(""));
// Throws exception: Console.WriteLine(untilSlash(null));


Console.WriteLine("443-2.jpg".GetUntilOrEmpty());
}
}

顺便说一下,正则表达式模式改为 "^(.*?)(-|$)"将允许拾取,直到 "-"模式或如果模式没有找到-拾取一切,直到字符串结束。

LINQy 方式

String. Concat (“223232-1.jpg”. TakeWhile (c = > c! =’-’))

(但是,您确实需要测试 null;)

对 C # ≥8的 Fredou 解稍作修改和更新

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

测试:

[TestCase("", ' ', ExpectedResult = "")]
[TestCase("a", 'a', ExpectedResult = "")]
[TestCase("a", ' ', ExpectedResult = "a")]
[TestCase(" ", ' ', ExpectedResult = "")]
[TestCase("/", '/', ExpectedResult = "")]
[TestCase("223232-1.jpg", '-', ExpectedResult = "223232")]
[TestCase("443-2.jpg", '-', ExpectedResult = "443")]
[TestCase("34443553-5.jpg", '-', ExpectedResult = "34443553")]
[TestCase("34443553-5-6.jpg", '-', ExpectedResult = "34443553")]
public string GetUntil(string input, char until) => input.GetUntil(until);