code_junkie

How can I split a C# string when a member of the array may consist of more than one word?

Nov 12th, 2011
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. string makeModel = csvArray[0]; // or whichever column it is in
  2. string[] makeAndModel = makeModel.Split( new char[] { ' ' } , 2 );
  3. string make = makeAndModel[0];
  4. string model = makeAndModel[1];
  5.  
  6. ,(?=([^"]*"[^"]*")*(?![^"]*"))
  7.  
  8. 123,456,"Unbalanced quote
  9.  
  10. int numFields = 4;
  11. string[] myFields = myLine.Split(' ');
  12.  
  13. int extraSpaces = myFields.length-numFields;
  14. if(extraSpaces>0) {
  15. // Piece together element 0 in the array by adding the extra elements
  16. for(int n = 1; n <= extraSpaces; n++) {
  17. myFields[0] += ' ' + myFields[n];
  18. }
  19. // Move the other values back to elements 1, 2, and 3 of the array
  20. for(int n = 1; n < numFields; n++) {
  21. myFields[n] = myFields[n + extraSpaces];
  22. }
  23. }
  24.  
  25. MatchCollection m = RegEx.Matches(myLine, "^(.*) ([^ ]+) ([^ ]+) ([^ ]+)$");
  26. string MakeModel = m.Groups[1].Captures[0].ToString();
  27. string ModelYear = m.Groups[2].Captures[0].ToString();
  28. string Price = m.Groups[3].Captures[0].ToString();
  29. string NumWheels = m.Groups[4].Captures[0].ToString();
  30.  
  31. string[] myFields = Microsoft.VisualBasic.Replace(myLine.Reverse(), " ", "_", 0, 3).Reverse().Split(' ');
  32. myFields[0] = myFields[0].Replace("_", " "); //fix the underscores
  33.  
  34. String.Split(Convert.ToChar(","));
Add Comment
Please, Sign In to add comment