使用String.Splitt()拆分字符串
本文关键字:拆分 字符串 String Splitt 使用 | 更新日期: 2023-09-27 18:25:01
我试图将字符串拆分为多个子部分,以传递到linq数据库中,但遇到了一个问题。该文件是.csv文件,因此用逗号分隔例如:
1,女士,Aleshia,Tomkiewicz,14 Taylor St,St。Stephens Ward,Kent,CT2第7页,01835-703597,atomkiewicz@hotmail.com.
然而,有些数据在数据字段中包含逗号,比如一个县/地址用逗号分隔,但我不希望它被分隔,我希望它把这些数据放在一起,例如地址:伦敦,温布尔登。
im using this code currently to do the chopping:
public static List<string> ReturnCSVFromWeb(string url)
{
System.Net.WebClient client = new WebClient();
string CSVContent = client.DownloadString(url);
List<string> splitted = new List<string>();
string csvFile = CSVContent;
string[] tempStr;
tempStr = csvFile.Split(',',''n');
foreach (string item in tempStr)
{
if (!string.IsNullOrWhiteSpace(item))
{
splitted.Add(item);
}
}
return splitted;
}
除非您提前知道哪些数据包含逗号,否则无法解决此问题。一个更好的选择是用双引号包围csv中的每个条目,然后用逗号分隔
如果行数是固定的(M
),并且只有地址列有逗号,则可以执行以下操作:
- 拆分行
- 取地址前的第一个
N1
列 - 取地址后的最后一个
N2
列 - 从中间取
M-N1-N2
列,将它们连接起来——这是一个地址