C# 拆分字符串并仅获取第一个值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10868517/
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-09 15:36:21  来源:igfitidea点击:

Split string and get first value only

c#

提问by 3D-kreativ

I wonder if it's possible to use split to devide a string with several parts that are separated with a comma, like this:

我想知道是否可以使用 split 来划分一个字符串,其中包含几个用逗号分隔的部分,如下所示:

title, genre, director, actor

I just want the first part, the title of each string and not the rest?

我只想要第一部分,每个字符串的标题而不是其余部分?

采纳答案by bhupendra patel

string valueStr = "title, genre, director, actor";
var vals = valueStr.Split(',')[0];

vals will give you the title

vals 会给你标题

回答by SimpleVar

Actually, there is a better way to do it than split:

实际上,有比拆分更好的方法:

public string GetFirstFromSplit(string input, char delimiter)
{
    var i = input.IndexOf(delimiter);

    return i == -1 ? input : input.Substring(0, i);
}

And as extension methods:

并作为扩展方法:

public static string FirstFromSplit(this string source, char delimiter)
{
    var i = source.IndexOf(delimiter);

    return i == -1 ? source : source.Substring(0, i);
}

public static string FirstFromSplit(this string source, string delimiter)
{
    var i = source.IndexOf(delimiter);

    return i == -1 ? source : source.Substring(0, i);
}

Usage:

用法:

string result = "hi, hello, sup".FirstFromSplit(',');
Console.WriteLine(result); // "hi"

回答by Ivo

You can do it:

你能行的:

var str = "Doctor Who,Fantasy,Steven Moffat,David Tennant";

var title = str.Split(',').First();

Also you can do it this way:

你也可以这样做:

var index = str.IndexOf(",");
var title = index < 0 ? str : str.Substring(0, index);

回答by Vityata

These are the two options I managed to build, not having the luxury of working with vartype, nor with additional variables on the line:

这是我设法构建的两个选项,没有使用var类型的奢侈,也没有在线上的附加变量:

string f = "aS.".Substring(0, "aS.".IndexOf("S"));
Console.WriteLine(f);

string s = "aS.".Split("S".ToCharArray(),StringSplitOptions.RemoveEmptyEntries)[0];
Console.WriteLine(s);

This is what it gets:

这是它得到的:

enter image description here

在此处输入图片说明