| ページ一覧 | ブログ | twitter |  書式 | 書式(表) |

MyMemoWiki

C Charp固定長分割

提供: MyMemoWiki
ナビゲーションに移動 検索に移動
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Text.RegularExpressions;
  7.  
  8. namespace FieldSplitter
  9. {
  10. public class FieldSplitterService
  11. {
  12. public string SplitField(string lengthString, string inputData, string splitChar)
  13. {
  14. var buf = new StringBuilder();
  15.  
  16. List<int> lengthList = GetLengthList(lengthString);
  17.  
  18. using (var reader = new StringReader(inputData))
  19. {
  20. string line = null;
  21. while((line = reader.ReadLine()) != null) {
  22. buf.Append(SplitLine(lengthList, splitChar ,line));
  23. buf.Append(Environment.NewLine);
  24. }
  25. }
  26. return buf.ToString();
  27. }
  28.  
  29. private string SplitLine(List<int> lengthList, string splitChar, string line)
  30. {
  31. var buf = new StringBuilder();
  32. int pos = 0;
  33. foreach(int len in lengthList)
  34. {
  35. if (len > 0)
  36. {
  37. int stepc = 0;
  38. int diflen = 0;
  39. for(int i=pos; i<line.Length; i++)
  40. {
  41. var c = line[i];
  42. if (((int)c) <= 255)
  43. {
  44. diflen += 1;
  45. }
  46. else
  47. {
  48. diflen += 2;
  49. }
  50. buf.Append(c);
  51. stepc++;
  52. if (diflen >= len)
  53. {
  54. break;
  55. }
  56. }
  57. pos += stepc;
  58. }
  59. buf.Append(splitChar);
  60. }
  61. if (pos < line.Length)
  62. {
  63. buf.Append(line.Substring(pos));
  64. }
  65.  
  66. return buf.ToString();
  67. }
  68.  
  69. private List<int> GetLengthList(string lengthList)
  70. {
  71. var strLenList = Regex.Split(lengthList, @"[^0-9]");
  72.  
  73. var ret = strLenList
  74. .Where(len => Regex.IsMatch(len, @"[0-9]+"))
  75. .Select(len => int.Parse(len));
  76.  
  77. return ret.ToList();
  78. }
  79.  
  80. }
  81. }