【发布时间】:2010-12-23 20:55:24
【问题描述】:
我正在尝试找出在字符串中 - 字符之前获取所有内容的最佳方法。下面是一些示例字符串。 - 之前的字符串长度不同,可以是任意长度
223232-1.jpg
443-2.jpg
34443553-5.jpg
所以我需要从起始索引 0 到 - 之前的值。所以子串会变成 223232、443 和 34443553
【问题讨论】:
我正在尝试找出在字符串中 - 字符之前获取所有内容的最佳方法。下面是一些示例字符串。 - 之前的字符串长度不同,可以是任意长度
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
【讨论】:
string result = source.Substring(0, Math.Max(source.IndexOf('-'), 0))
s 的长度严格超过n 时,可以使用s.Remove(n) 而不是s.Remove(n)。
String str = "223232-1.jpg"
int index = str.IndexOf('-');
if(index > 0) {
return str.Substring(0, index)
}
【讨论】:
一种方法是将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 开始,返回所有文本直到破折号,但不包括破折号。
【讨论】:
使用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.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;
}
【讨论】:
您可以为此目的使用正则表达式,但是当输入字符串与正则表达式不匹配时,最好避免额外的异常。
首先要避免转义到正则表达式模式的额外头痛 - 我们可以为此目的使用函数:
String reStrEnding = Regex.Escape("-");
我知道这不会做任何事情 - 因为“-”与 Regex.Escape("=") == "=" 相同,但如果字符是 @"\",它会有所不同。
然后我们需要从字符串的请求匹配到字符串结尾,或者如果没有找到结尾 - 则不匹配。 (空字符串)
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());
}
}
顺便说一句 - 将正则表达式模式更改为 "^(.*?)(-|$)" 将允许拾取直到 "-" 模式或者如果未找到模式 - 拾取所有内容直到字符串结束。
【讨论】:
LINQy 方式
String.Concat("223232-1.jpg".TakeWhile(c => c != '-'))
(但是,您确实需要测试 null ;)
【讨论】:
..)/// <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);
【讨论】: