我正在尝试找出获取字符串中 - 字符之前的所有内容的最佳方法。下面是一些示例字符串。之前字符串的长度 - 各不相同,可以是任意长度
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
使用split功能。
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 str = "223232-1.jpg";
int index = str.IndexOf('-');
if(index > 0) {
return str.Substring(0, index);
}
自从这个帖子开始以来,事情已经发生了一些变化。
现在,你可以使用
string.Concat(s.TakeWhile((c) => c != '-'));
实现此目的的一种方法是将
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
}
从位置 0 开始,返回直到破折号(但不包括破折号)的所有文本。
/// <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);
LINQy 方式
String.Concat( "223232-1.jpg".TakeWhile(c => c != '-') )
(但是,您确实需要测试 null ;)
以 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;
}
您可以使用正则表达式来实现此目的,但最好避免输入字符串与正则表达式不匹配时出现额外的异常。
首先要避免转义到正则表达式模式带来的额外麻烦 - 我们可以使用函数来达到此目的:
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());
}
}
顺便说一句 - 将正则表达式模式更改为
"^(.*?)(-|$)"
将允许拾取直到 "-"
模式,或者如果未找到模式 - 拾取所有内容直到字符串末尾。