我试图弄清楚在字符串中的字符之前获取所有内容的最佳方法.下面是一些示例字符串.之前字符串的长度 - 变化,可以是任何长度
223232-1.jpg
443-2.jpg
34443553-5.jpg
Run Code Online (Sandbox Code Playgroud)
所以我需要从起始索引0到右前的值 - .所以子串会变成223232,443和34443553
Fre*_*dou 123
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)
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)
如果你的字符串没有,-
那么你将得到整个字符串.
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)
/// <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
自从该线程启动以来,情况有所发展。
现在,您可以使用
string.Concat(s.TakeWhile((c) => c != '-'));
Run Code Online (Sandbox Code Playgroud)
一种方法是与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 开始,返回直到破折号(但不包括破折号)的所有文本。
归档时间: |
|
查看次数: |
247959 次 |
最近记录: |