简体   繁体   English

分割逗号分隔的字符串并存储到变量中

[英]Split comma separated string and store into variables

I want to split a string and store every data to variable in C#. 我想分割一个字符串并将每个数据存储到C#中的变量中。 How can I achieve that ? 我该如何实现?

My code is: 我的代码是:

string name="John,Hutkins,Doe,San Francisco CA";

Output should be this: 输出应为:

string fname = "John";
string mname = "Hutkins";
string lname = "Doe";
string address= "San Francisco CA";

Its as simple as : 它很简单:

var results = name.Split(',');

if(results.Length != 4)
 throw new InvalidOperationException("Oh Noes!!!");

string fname = results[0];
string mname =  results[1];
string lname =  results[2];
string address=  results[3];

Warning the second you have a comma in your address, this is going to fail. 警告您地址中第二个逗号,这将失败。

If this is a CSV file, consider using a dedicated CSV Parser, there are plenty 如果这是CSV文件,请考虑使用专用的CSV分析器,

Further reading 进一步阅读

String.Split Method String.Split方法

Returns a string array that contains the substrings in this instance that are delimited by elements of a specified string or Unicode character array. 返回一个字符串数组,该数组包含此实例中的子字符串,这些子字符串由指定字符串或Unicode字符数组的元素定界。

Looks like the case where it is better having a class 看起来最好是上课

public class PersonalInfo 
{

    public FName { get; private set; }
    public LName { get; private set; }
    public MName { get; private set; }
    public Address { get; private set; }

    public PersonalInfo (string info)
    {
        string[] items = info.Split(',');
        FName = items [0];
        MName = items [1];
        LName = items [2];
        Address = items [3];

    }

    public override ToString()
    {
       // return $"{LName}, {FName} {MName}"; // vs 2017
       return string.Format("{0}, {1} {2}", LName, FName, MName); // vs 2008
    }


}

Now you can actually use your objects in lists etc. 现在,您可以实际在列表等中使用对象了。

var pi = new PersonalInfo("John,Hutkins,Doe,San Francisco CA");
textBox1.Text = pi.FName;
. . . . . . . 

If this string is from .csv file consider using an available csv parser. 如果此字符串来自.csv文件,请考虑使用可用的csv解析器。 Any way you can use this methid as well. 您也可以使用任何方法使用此方法。

String [] results = name.Split(',');

In here your names will be stored in the results array. 在这里,您的姓名将存储在结果数组中。 The index order will be the names order in the string starting with 0; 索引顺序将是字符串中以0开头的名称顺序。 Like this 像这样

String address = results[3];

But there is a mistake here. 但是这里有一个错误。 Since you are using the comma to separate the values you cannot use Commas in the address which will be hard. 由于您使用逗号分隔值,因此您无法在地址中使用逗号,这会很困难。 Try using something like '|' 尝试使用“ |”之类的东西 od '*'. od'*'。

Regards 问候

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM