2012-04-13 233 views
-1

我正在编写一个控制台应用程序,它从csv文件读入并将文件中的每个元素存储到一个字符串数组中。有一种方法需要遍历数组中的每个字符串,并删除所有非alpha字符和空格。我使用regex.replace()方法成功完成了这个操作,但是一旦我尝试使用字符串数组进行更改,就会发生更改。然后我继续尝试使用string.replace(),但无济于事。我认为正则表达式路径是更好的选择,但我没有成功。如果有人能帮助我,我将不胜感激。以下是我的代码:字符串替换()/正则表达式替换 - 替换字符串数组中的字符串?

public static string[] ChangeAddress(string[] address) 
    { 
     for (int i = 0; i < address.Length; i++) 
     { 
      Regex.Replace(i, @"(\s-|[^A-Za-z])", ""); 
      System.Console.WriteLine(address[i]); 
     } 
     return address; 
    } 

    static void Main(string[] args) 
    { 
     string[] address = null; 
     //try...catch read file, throws error if unable to read 
     //reads file and stores values in array 
     try 
     { 
      StreamReader sr = new StreamReader("test.csv"); 
      string strLine = ""; 
      //while not at the end of the file, add to array 
      while (!sr.EndOfStream) 
      { 
       strLine = sr.ReadLine(); 
       address = strLine.Split(','); 
      } 
     } 
     catch (Exception e) 
     { 
      Console.WriteLine("File could no be read:"); 
      Console.WriteLine(e.Message); 
     } 

     //calls ChangeAddress method 
     ChangeAddress(address); 
    } 

csv文件包含用逗号分隔的不同地址。我的目标是删除数字并留下仅有的街道名称。例如,原始字符串可能是123假,目标是删除“123”,因此它将被替换为“假”。我想对数组中的每个元素执行此操作。

+0

您是否阅读过[Regex.Replace]的MSDN页面(http://msdn.microsoft.com/zh-cn/library/h0y2x3xs.aspx)? (A)它_returns_一个字符串和(B)不接受一个整数作为第一个参数,所以这将不会按原样编译。 – 2012-04-13 16:26:44

+0

除非您的实际代码与本示例有所不同,否则您只会从地址阵列中的文件中获取最后一个地址。您在while循环的每次迭代中覆盖它。 – pstrjds 2012-04-13 16:31:39

回答

2

您需要在替换时对结果进行一些处理,类似的操作应该可以修复它。

public static string[] ChangeAddress(string[] address) 
{ 
    for (int i = 0; i < address.Length; i++) 
    { 
     address[i] = Regex.Replace(address[i], @"(\s-|[^A-Za-z])", ""); 
     System.Console.WriteLine(address[i]); 
    } 
    return address; 
} 

这里的关键是,你必须将价值传递到RegEx.Replace并更新你的阵列。

+0

哇。我感觉这很简单。非常感谢你! – mpcc12 2012-04-13 16:37:47

1

除了米切尔的答案,这是一个问题:

StreamReader sr = new StreamReader("test.csv"); 
string strLine = ""; 

//while not at the end of the file, add to array 
while (!sr.EndOfStream) 
{ 
    strLine = sr.ReadLine(); 
    address = strLine.Split(','); 
} 

...,可与File.ReadAllLines更换:

addresses = File.ReadAllLines("test.csv"); 

您可以使用File.ReadLines,并在飞行固定地址:

var addresses = new List<string>(); 
foreach(var address in File.Readlines("test.csv")) 
{ 
    var corrected = Regex.Replace(address, @"(\s-|[^A-Za-z])", ""); 
    addresses.Add(corrected); 
} 
+0

我刚刚添加这个作为评论,当你添加这个。我在想着ReadAllLines,除了那时你需要另外一次分割线。使用'List '可能会更好(可能),并保留流读取器并将分隔线添加到列表中。 – pstrjds 2012-04-13 16:32:52

+0

@pstrjds:你说得对,但是OP已经进行了两遍(阅读并稍后调用ChangeAddress) – 2012-04-13 16:34:14

0

为什么不应用正则表达式replaceme nt strLine之前,你把它放入你的地址数组?你可能只是做类似如下:

 
`Regex.Replace(strLine, @"(\s-|[^A-Za-z])", "");` 
`address = strLine.Split(',');` 

当然,你可能要修改你的正则表达式不删除“,的为好。