我必须解析这个字符串
"Cust =Customer CustCR =Customer Credit Prod=Product SalesRep=Sales Rep TaxCat=Tax Category TaxId=Tax ID VolBill=Volume Billing"
代码,描述如Code = Cust和Description = Customer
基于空格分割不起作用,因为描述中也有空格。
答案 0 :(得分:4)
您可以在等号上拆分,而不是在空间上拆分。然后代码将是前一项的最后一个空格之后的值,描述将是最后一个空格的所有内容,确保修剪可能在等于之前显示的空格。您可以将Dictionary
替换为要将值加载到的任何数据类型。此外,您必须处理第一个和最后一个值作为特殊情况。请注意,这仅在代码不包含空格时才有效。
string str = "Cust =Customer CustCR =Customer Credit Prod=Product SalesRep=Sales Rep TaxCat=Tax Category TaxId=Tax ID VolBill=Volume Billing";
var separated = str.Split('=');
string code = separated[0].Trim();
var codeAndDescription = new Dictionary<string, string>();
for (int i = 1; i < separated.Length - 1; i++)
{
int lastSpace = separated[i].Trim().LastIndexOf(' ');
var description = separated[i].Substring(0, lastSpace).Trim();
codeAndDescription.Add(code, description);
code = separated[i].Substring(lastSpace + 1).Trim();
}
codeAndDescription.Add(code, separated[separated.Length - 1]);
foreach (var kvp in codeAndDescription)
Console.WriteLine(kvp);
输出
[客户,客户]
[CustCR,客户信用]
[产品] [产品]
[SalesRep,销售代表]
[TaxCat,Tax Category]
[TaxId,Tax ID]
[VolBill,Volume Billing]
答案 1 :(得分:1)
class Item {
public string Code { get; set; }
public string Description { get; set; }
}
class Program
{
static void Main(string[] args)
{
string str = "0= 1=Full Time 2=Part Time 3=Seasonal 4=Variable";
var separated = str.Split('=');
string code = separated[0].Trim();
var codeAndDescription = new List<Item>();
foreach (var sep in separated.Skip(1).Take(separated.Length - 2))
{
int lastSpace = sep.Trim().LastIndexOf(' ');
var description = lastSpace != -1 ? sep.Substring(0, lastSpace).Trim(): "" ;
codeAndDescription.Add(new Item { Code=code,Description=description });
code = sep.Substring(lastSpace + 1).Trim();
}
codeAndDescription.Add(new Item { Code = code, Description = separated.Last() });
foreach (var kvp in codeAndDescription)
{
Console.WriteLine("Code={0} Description={1}", kvp.Code, kvp.Description);
}
Console.ReadLine();
}
}