c# - 如何在C#中用空格分割字符串
问题描述
我有一份药物清单,每行包含其商业名称、INN、剂量和形式等。
00148ASPEGIC ACETYLSALICYLATE DE LYSINE 900 MG B/6 O 0 071 OOO 05703A00497 P
00149SPRIDOL ACETYLSALICYLATE DE LYSINE 900 MG B/6 O 0 004 OOO 19303A00499 G
00150SPRIDOL ACETYLSALICYLATE DE LYSINE 900MG MG B/1 O 0 004 OOO 19303A00499 G
00151ASPEGIC ACETYLSALCICYLATE DE LYSINE 1 G B/6 AMP O 0 071 OO 05703A02398 P
00152ASPEGIC ACETYLSALICYLATE DE LYSINE 250MG MG B/20 SACHETS O19072003 11760 047 OOO 25503A0240302102008 P 10
00153ASPEGIC ACETYLSALICYLATE DE LYSINE 500MG MG B/20 O 6680 047 OOO 05703A02597 P213 10
我只需要从前五列中检索数据,如下所示:
ASPEGIC | ACETYLSALCICYLATE DE LYSINE | 1G | B/6 AMP
到目前为止我用来拆分的代码是
using (StreamReader sr = new StreamReader("medic.txt"))
{
while (sr.Peek() > 0)
{
string line = sr.ReadLine();
var pts = line.Split(" ", StringSplitOptions.RemoveEmptyEntries);
Array.ForEach(pts, Console.WriteLine);
}
}
解决方案
数据是固定宽度的列,因此请使用以下内容:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.txt";
static void Main(string[] args)
{
FIX_WIDTH fixWidth = new FIX_WIDTH(FILENAME);
}
}
public class FIX_WIDTH
{
int[] Start_Position = { 0, 55, 105, 135, 155, 176, 207, 215, 219, 223, 243, 264};
string[] Column_Names = { "Col_A", "Col_B", "Col_C", "Col_D", "Col_E", "Col_F", "Col_G", "Col_H", "Col_I", "Col_J", "Col_K", "Col_L" };
public DataTable dt;
public FIX_WIDTH(string filename)
{
dt = new DataTable();
foreach (string col in Column_Names)
{
dt.Columns.Add(col, typeof(string));
}
StreamReader reader = new StreamReader(filename);
string line = "";
while ((line = reader.ReadLine()) != null)
{
line = line.Trim();
if (line.Length > 0)
{
List<string> row = new List<string>();
for (int i = 0; i < Start_Position.Length; i++ )
{
int pos = Start_Position[i];
if (pos >= line.Length)
{
break;
}
else
{
if (i == Start_Position.Length - 1)
{
row.Add(line.Substring(pos).Trim());
}
else
{
int length = Start_Position[i + 1] - pos;
if (pos + length <= line.Length)
{
row.Add(line.Substring(pos, length).Trim());
}
else
{
row.Add(line.Substring(pos).Trim());
}
}
}
}
dt.Rows.Add(row.ToArray());
}
}
}
}
}
推荐阅读
- jmeter - 如何使用JMeter多次执行soap请求的中间部分?
- ios - 如何使用 Xcode 9.x 在自定义项目模板中添加“带有文件夹的新组”?
- r - 使用多图但只使用一个图
- ios - 自动调整collectionview单元格不能以最小的行空间正确显示
- c++ - Qt3D 中的内存泄漏
- android - 取消时 Android Google 登录错误
- node.js - 避免传递临时 Promise 对象
- apache-kafka - 将 debezium 任务提交到融合连接时,创建数据库历史主题失败
- amazon-web-services - aws fargate 为环境变量添加参数
- c# - 从 C# 应用程序关闭 IE 弹出窗口