C Charp固定長分割
ナビゲーションに移動
検索に移動
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace FieldSplitter
{
public class FieldSplitterService
{
public string SplitField(string lengthString, string inputData, string splitChar)
{
var buf = new StringBuilder();
List<int> lengthList = GetLengthList(lengthString);
using (var reader = new StringReader(inputData))
{
string line = null;
while((line = reader.ReadLine()) != null) {
buf.Append(SplitLine(lengthList, splitChar ,line));
buf.Append(Environment.NewLine);
}
}
return buf.ToString();
}
private string SplitLine(List<int> lengthList, string splitChar, string line)
{
var buf = new StringBuilder();
int pos = 0;
foreach(int len in lengthList)
{
if (len > 0)
{
int stepc = 0;
int diflen = 0;
for(int i=pos; i<line.Length; i++)
{
var c = line[i];
if (((int)c) <= 255)
{
diflen += 1;
}
else
{
diflen += 2;
}
buf.Append(c);
stepc++;
if (diflen >= len)
{
break;
}
}
pos += stepc;
}
buf.Append(splitChar);
}
if (pos < line.Length)
{
buf.Append(line.Substring(pos));
}
return buf.ToString();
}
private List<int> GetLengthList(string lengthList)
{
var strLenList = Regex.Split(lengthList, @"[^0-9]");
var ret = strLenList
.Where(len => Regex.IsMatch(len, @"[0-9]+"))
.Select(len => int.Parse(len));
return ret.ToList();
}
}
}
© 2006 矢木浩人