C# 获取子字符串 - 特定字符之前的所有内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1857513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 21:26:17  来源:igfitidea点击:

Get Substring - everything before certain char

c#

提问by PositiveGuy

I'm trying to figure out the best way to get everything before the - character in a string. Some example strings are below. The length of the string before - varies and can be any length

我试图找出在字符串中的 - 字符之前获取所有内容的最佳方法。下面是一些示例字符串。之前字符串的长度 - 变化并且可以是任意长度

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

so I need the value that's from the start index of 0 to right before -. So the substrings would turn out to be 223232, 443, and 34443553

所以我需要从 0 开始索引到 - 之前的值。所以子串将变成 223232、443 和 34443553

采纳答案by Fredou

.Net Fiddle example

.Net 小提琴示例

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

Results:

结果:

223232
443
34443553
344

34

回答by BrainCore

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

回答by Michael Petrotta

One way to do this is to use String.Substringtogether with String.IndexOf:

一种方法是与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
}

Starting at position 0, return all text up to, but not including, the dash.

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

回答by Dominic Cronin

Use the splitfunction.

使用拆分功能。

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

If your string doesn't have a -then you'll get the whole string.

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

回答by Anthony Wieser

Things have moved on a bit since this thread started.

自从这个线程开始以来,事情已经发生了一些变化。

Now, you could use

现在,你可以使用

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

回答by n122vu

Building on BrainCore's answer:

基于 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;
    }

回答by TarmoPikaro

You can use regular expressions for this purpose, but it's good to avoid extra exceptions when input string mismatches against regular expression.

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

First to avoid extra headache of escaping to regex pattern - we could just use function for that purpose:

首先为了避免转义到正则表达式模式的额外麻烦 - 我们可以为此目的使用函数:

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

I know that this does not do anything - as "-" is the same as Regex.Escape("=") == "=", but it will make difference for example if character is @"\".

我知道这并不做任何事情-为“ - ”是一样的Regex.Escape("=") == "=",但它会使差异,例如,如果性格@"\"

Then we need to match from begging of the string to string ending, or alternately if ending is not found - then match nothing. (Empty string)

然后我们需要从字符串的开始匹配到字符串结尾,或者如果没有找到结尾 - 那么什么都不匹配。(空字符串)

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

If your application is performance critical - then separate line for new Regex, if not - you can have everything in one line.

如果您的应用程序对性能至关重要 - 然后为新的 Regex 单独一行,否则 - 您可以将所有内容放在一行中。

And finally match against string and extract matched pattern:

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

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

And after that you can either write separate function, like it was done in another answer, or write inline lambda function. I've wrote now using both notations - inline lambda function (does not allow default parameter) or separate function call.

之后,您可以编写单独的函数,就像在另一个答案中所做的那样,或者编写内联 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());
    }
}

Btw - changing regex pattern to "^(.*?)(-|$)"will allow to pick up either until "-"pattern or if pattern was not found - pick up everything until end of string.

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

回答by Den

The LINQy way

LINQy 方式

String.Concat( "223232-1.jpg".TakeWhile(c => c != '-') )

String.Concat( "223232-1.jpg".TakeWhile(c => c != '-') )

(But, you do need to test for null ;)

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