0

Removing part of an array

So currently I have the following code

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));
    }
}

Currently I get the following result

Boundary Rd
Boswell Terrace
100 Lockrose St
Williams Ave
sunnybank hills

I was wondering if there was a way that I could, instead of removing characters, remove the first three words. For example if I have an array

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

I want to remove every first three words in this array which will leave me with this as a result if i print to console.

st sunnybank hills

Tyress
  • 3,573
  • 2
  • 22
  • 45
  • 3
    But "st sunnybank hills" isn't "every 3rd word in this array;" it's the last three words in the last item in the array. Is that what you meant? – jgfооt Feb 23 '16 at 03:13

2 Answers2

1

Based on your example, what you want is to remove the first three words and not every 3rd word:

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)));
}
Tyress
  • 3,573
  • 2
  • 22
  • 45
  • How would i print these results to a new file? Keeping all blank lines etc – Dillon Munien Feb 23 '16 at 03:38
  • No problem @DillonMunien ! For printing to a file, you can look around on SO to do that, but [here](http://stackoverflow.com/a/7306243/1685167)'s an example. Just put the foreach inside of the `using StreamWriter` block (where sw.WriteLine()) is, and instead of `Console.WriteLine()`, use `sw.WriteLine()` – Tyress Feb 23 '16 at 03:49
  • Thanks i got it working :), also if i wanted to do the opposite and remove everything after the 3 words how would i do that? – Dillon Munien Feb 23 '16 at 04:04
  • Replace Skip() with Take() ;) – Tyress Feb 23 '16 at 04:49
0

Here is regular expression way:

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, ""));
}

[^ ] match any character except space.

NoName
  • 7,940
  • 13
  • 56
  • 108