简体   繁体   English

使用String.Split()分割字符串

[英]Splitting a String using String.Split()

Im trying to split a string into sub parts to pass into a linq database, but ive come up with a problem. 我试图将字符串拆分为多个子部分,以传递到linq数据库,但我想出了一个问题。 The file is a .csv file so its split up by commas example : 该文件是.csv文件,因此可以用逗号分隔:

1,Ms,Aleshia,Tomkiewicz,14 Taylor St,St. 1,女士,Aleshia,Tomkiewicz,14 Taylor St,St。 Stephens Ward,Kent,CT2 7PP,01835-703597,atomkiewicz@hotmail.com. Stephens Ward,肯特,CT2 7PP,01835-703597,atomkiewicz @ hotmail.com。

However some of the data contains commas in the data field like a county/address is split up with a comma however i dont want it to split i want it to keep that data all together for example address: London,Wimbledon. 但是,某些数据在数据字段中包含逗号,例如县/地址用逗号分隔,但是我不希望将其分隔,我希望将所有数据都保持在一起,例如地址:伦敦,温布尔登。

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;

        }

There is no way to solve this problem unless you know ahead of time which data contains commas. 除非您提前知道哪些数据包含逗号,否则无法解决此问题。 A better option would be to have each entry in the csv surrounded by double quote, and then seperated by comma 更好的选择是让csv中的每个条目都用双引号引起来,然后用逗号分隔

If number of rows is fixed ( M ) and only address column has comma, you can do this: 如果行数是固定的( M )并且只有地址列具有逗号,则可以执行以下操作:

  1. Split row 分割行
  2. Take first N1 columns before address 在地址前获取前N1
  3. Take last N2 columns after address 在地址后取最后N2
  4. Take M-N1-N2 columns from middle, join them - it's an address 从中间取出M-N1-N2列,将它们加入-这是一个地址

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

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