简体   繁体   中英

C# - Merging strings from a certain position

I want to create a function but I don't know how it would work or how to create it. I want to create a function something similar to below.

I have a string, lets say its this for example:

string myString = "This is my string and it will forever be my string.";

What if I wanted to split this by a space and get each part? which I do...

string[] parts = myString.Split(' ');

Now, I want to get everything but the first 3 words in my string parts, how would I merge each string in parts except the first 3? which will return

string and it will forever be my string.

Something similar to this:

public string getMergedString(string[] parts, int start) // This method would return everything from where you told it to start...
{

}
public string getMergedString(string[] parts, int start) // This method would return everything from where you told it to start...
{
    return String.Join(" ", parts.Skip(start));
}

Quick explanation of the code:

string.Join(separator, IEnumerable values)

This joins an IEnumerable object containing strings to one, unified string.

Docs: https://msdn.microsoft.com/en-us/library/system.string.join(v=vs.110).aspx

parts.Skip(int count)

This part of the code skips a given amount of elements, before returning them. Skip(int count) is an extension method found in the System.Linq namespace. You need .Net 3.5 or higher in order for you to be able to use this method.

Docs: https://msdn.microsoft.com/en-us/library/bb358985(v=vs.110).aspx

            string myString = "This is my string and it will forever be my string.";
        string[] words = myString.Split(' ');
        var myNewString = string.Join(" ", words.Skip(3));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM