如何获取固定的字符串数组 [英] How to get fixed array of string

查看:127
本文介绍了如何获取固定的字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要求从文件中读取一行,将其转换为数组,然后将其保存到db中. a b c d e array1> a b d e


在第一种情况下,我具有5个索引的数组,在第二种情况下,我具有4个索引的数组,
我希望每次得到5个索引数组,该索引没有值,对它返回",我使用以下代码将字符串转换为数组,

 字符串 test = strtext;
                       字符串 []结果= Regex.Split(test," );
                        for ( int  i =  11 ; i < result.Length; i ++)
                       {
                           // 字符串test1 = result [i]; 
                           字符串 [] strArr = ;
                         //  int count = 0; 
                           字符串 str = result [i];
                           字符 [] splitchar = {' ' };
                           strArr = str.Split(splitchar);

解决方案

如果我正确理解了您的问题,那么即使在文本文件为空白.

您可以使用相当简单的正则表达式来做到这一点.

 私有 静态正则表达式colExpr =  new  Regex( @" ); 


该表达式基本上意味着首先要顺序查找2个空白,然后再查找1个空白.

然后使用分割功能,该功能将在找到匹配项的位置分割字符串.

 字符串 line1 = " ;
字符串 line2 = " ;

字符串 [] res1 = colExpr.Split(line1);
字符串 [] res2 = colExpr.Split(line2); 


这两个拆分都将为您提供一个具有5个位置的数组,但是对于第二行,位置3将为空.

因此,如果您逐行阅读文件,则此解决方案将为您工作.


i have requirement that to read a line from a file ,convert it into array and then save it into db,

array1> a b c d e
array1> a b   d e


in first case i have array of 5 index ,in second case i have array of 4 index,
i want that i get 5 index array every time,which index has no value return "" against it,i use following code to convert string to array,

string test = strtext;
                       string[] result = Regex.Split(test, "\n\\s*");
                       for (int i = 11; i <result.Length; i++)
                       {
                           //string test1 = result[i];
                           string[] strArr = null;
                         //  int count = 0;
                           string str = result[i];
                           char[] splitchar = { ' ' };
                           strArr = str.Split(splitchar);

解决方案

If I understand your question correctly, you want to always get an array with 5 positions as the result, even if a "column" in the text file is blank.

You can do this with a rather simple regular expression.

private static Regex colExpr = new Regex(@" {2}| ");


The expression basically means that first look for 2 white spaces in sequence and then for 1 white space.

And then use the Split function that will split the string where a match is found.

string line1 = "a b c d e";
string line2 = "a b   d e";

string[] res1 = colExpr.Split(line1);
string[] res2 = colExpr.Split(line2);


Both splits will give you an array with 5 positions, but for the second line position 3 will be empty.

So if you read your file line by line, this solution should work for you.


这篇关于如何获取固定的字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆