1
private static string SetValue(string input, string reference)
{
    string[] sentence = input.Split(' ');
    for(int word = 0; word<sentence.Length; word++)
    {
        if (sentence[word].Equals(reference, StringComparison.OrdinalIgnoreCase))
        {
            return String.Join(" ", sentence.subarray(word+1,sentence.Length))
        }
    }
}

How can I accomplish sentence.subarray(word+1,sentence.Length) easily or do this in another way?

1

4 Answers 4

5

String.Join has an overload specifically for this:

return String.Join(" ", sentence, word + 1, sentence.Length - (word + 1));
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I didn't notice that! :D
1

You can use an overload Where with index:

return string.Join(" ", sentence.Where((w, i) => i > word));

2 Comments

Don't do this. X.Where((x, i) => i > I) gives the same results as X.Skip(I + 1) but is marginally less efficient and takes longer to figure out.
@Rawling: that's true, just another approach, but don't fall down much on pre-mature optimization, I like the approach using SKip(word + 1), it's simpler.
1

If you are strictly looking for a Subarray solution independent of the string.Join() function, and you are using a version of .NET with Linq support, then may I recommend:

sentence.Skip(word + 1);

2 Comments

My original answer included a ToArray() call at the end since a .NET version of subarray was requested.
Just go ahead and edit it back, and hopefully no-one else will "correct" it for you.
0

Alternatively, you could use SkipWhile instead of your for loop.

private static string SetValue(string input, string reference)
{
    var sentence = input.Split(" ");
    // Skip up to the reference (but not the reference itself)
    var rest = sentence.SkipWhile( 
        s => !s.Equals(reference, StringComparison.OrdinalIgnoreCase));
    rest = rest.Skip(1); // Skip the reference
    return string.Join(" ", rest);
}

5 Comments

Doesn't SkipWhile include the item for which the predicate is true?
Also, I'm not sure Enumerable has Join. You might need to add ToArray after Skip(1).
IEnumerable<string> has a Join Method, but it's not the Join Method you mean. However, the String.Join Method has an overload that takes an IEnumerable<string>.
And now you need to add a few semicolons and variable declarations to make it actually compile :-)
Right. Too much Ruby lately ^^'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.