使用子串时比较数组

时间:2016-02-23 02:59:40

标签: c# arrays

删除数组的一部分

所以目前我有以下代码

public static void ReadSuburbs()
{
    String directory = @"C:\Address Sorting\";
    string[] linesA = new string[5] 
    { 
        "41 Boundary Rd", 
        "93 Boswell Terrace", 
        "4/100 Lockrose St", 
        "32 Williams Ave", 
        "27 scribbly gum st sunnybank hills"
    };

    int found = 0;
    foreach (string s in linesA)
    {
        found = s.IndexOf("st");
        Console.WriteLine(s.Substring(found + 3));
    }
}

目前我得到以下结果

  

边界路

  博斯韦尔露台
  100 Lockrose St
  Williams Ave
  sunnybank丘陵

我想知道我是否有办法,而不是删除字符,删除前三个单词。例如,如果我有一个数组

string[] linesA = new string[5] 
{ 
    "41 Boundary Rd", 
    "93 Boswell Terrace", 
    "4/100 Lockrose St", 
    "32 Williams Ave", 
    "27 scribbly gum st sunnybank hills"
};

我想删除此数组中的前三个单词,如果我打印到控制台,将会留下这个结果。

  

st sunnybank hills

2 个答案:

答案 0 :(得分:1)

根据您的示例,您想要的是删除前三个单词而不是每个第三个单词:

string[] linesA = new string[5] { "41 Boundary Rd", "93 Boswell Terrace", "4/100 Lockrose St", "32 Williams Ave", "27 scribbly gum st sunnybank hills"};
foreach (string line in linesA)
{
    string[] words = line.Split(' ');
    Console.WriteLine(string.Join(" ",words.Skip(3)));
}

答案 1 :(得分:0)

这是正则表达方式:

string[] linesA = new string[5] { "41 Boundary Rd", "93 Boswell Terrace", "4/100 Lockrose St", "32 Williams Ave", "27 scribbly gum st sunnybank hills" };
Regex r = new Regex(@"^[^ ]* [^ ]* [^ ]* *");
foreach (string s in linesA)
{
    Console.WriteLine(r.Replace(s, ""));
}

[^ ]匹配除空格之外的任何字符。