Answers:
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 result = source.Substring(0, Math.Max(source.IndexOf('-'), 0))
s.Substring(0, n)可以使用代替。s.Remove(n)sn
使用分割功能。
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();
}
如果您的字符串没有a,-那么您将获得整个字符串。
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开始,返回直到破折号(但不包括破折号)的所有文本。
您可以为此使用正则表达式,但是最好避免输入字符串与正则表达式不匹配时出现额外的异常。
首先,要避免转义到正则表达式模式的额外麻烦-我们可以为此使用函数:
String reStrEnding = Regex.Escape("-");
我知道这不会做任何事情-因为“-”与相同Regex.Escape("=") == "=",但是例如character是会有所不同@"\"。
然后,我们需要从字符串的乞求到字符串结尾匹配,或者如果找不到结尾,则进行匹配-然后不匹配。(空字符串)
Regex re = new Regex("^(.*?)" + reStrEnding);
如果您的应用程序对性能至关重要-如果不是,则为新的Regex单独一行-您可以将所有内容放在一行中。
最后匹配字符串并提取匹配的模式:
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());
}
}
顺便说一句-将正则表达式模式更改为"^(.*?)(-|$)"将允许拾取直到"-"模式或未找到模式-拾取所有内容直到字符串结尾。