Joh*_*ann 1 .net c# string split
我有这个字符串MIL_A_OP=LI_AND=SSB12=JL45==DO=90==IT=KR002112
,我需要将它拆分为2,基于第一个"="
所以我需要它得到:
第一个字符串 MIL_A_OP
第二串: LI_AND=SSB12=JL45==DO=90==IT
这下面的代码是我的,但它给了我MIL_A_OP和LI_AND,我想念其余的
try
{
StreamReader file1 = new StreamReader(args[0]);
string line1;
while ((line1 = file1.ReadLine()) != null)
{
if (line1 != null && line1.Trim().Length > 0)//if line is not empty
{
int position_1 = line1.IndexOf('=');
string s_position_1 = line1.Substring(position_1, 1);
char[] c_position_1 = s_position_1.ToCharArray(0,1);
string[] line_split1 = line1.Split(c_position_1[0]);
Foo.f1.Add(line_split1[0], line_split1[1]);
}
}
file1.Close();
}
catch (Exception e)
{
Console.WriteLine("File " + args[0] + " could not be read");
Console.WriteLine(e.Message);
}
Run Code Online (Sandbox Code Playgroud)
您希望Split()方法的重载允许您指定要返回的最大元素数.试试这个:
string[] line_split1 = line1.Split( new char[]{'='}, 2 );
Run Code Online (Sandbox Code Playgroud)
更新了Matthew的反馈.
请尝试以下方法
string all = "MIL_A_OP=LI_AND=SSB12=JL45==DO=90==IT=KR002112";
int index = all.IndexOf('=');
if (index < 0) {
throw new Exception("Bad data");
}
var first = all.Substring(0, index);
var second = all.Substring(index + 1, all.Length - (index + 1));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1955 次 |
| 最近记录: |