2012-04-13 230 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(',');` 

當然,你可能要修改你的正則表達式不刪除「,的爲好。