Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split and then Joining the String step by step - C# Linq

Tags:

c#

linq

Here is my string:

www.stackoverflow.com/questions/ask/user/end

I split it with / into a list of separated words:myString.Split('/').ToList()

Output:

www.stackoverflow.com
questions
ask
user
end

and I need to rejoin the string to get a list like this:

www.stackoverflow.com
www.stackoverflow.com/questions
www.stackoverflow.com/questions/ask
www.stackoverflow.com/questions/ask/user
www.stackoverflow.com/questions/ask/user/end

I think about linq aggregate but it seems it is not suitable here. I want to do this all through linq

like image 670
Inside Man Avatar asked Jun 13 '18 10:06

Inside Man


People also ask

What split () and join () method Why & Where it is used?

the split() method in Python split a string into a list of strings after breaking the given string by the specified separator. Python String join() method is a string method and returns a string in which the elements of the sequence have been joined by the str separator.

How do I split a string into string?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

Can you split a string in C?

In C, the strtok() function is used to split a string into a series of tokens based on a particular delimiter. A token is a substring extracted from the original string.


1 Answers

You can try iterating over it with foreach

var splitted = "www.stackoverflow.com/questions/ask/user/end".Split('/').ToList();
string full = "";
foreach (var part in splitted)
{
    full=$"{full}/{part}"
    Console.Write(full);
}

Or use linq:

var splitted = "www.stackoverflow.com/questions/ask/user/end".Split('/').ToList();
var list = splitted.Select((x, i) => string.Join("/", a.Take(i + 1)));
like image 117
Kamil Budziewski Avatar answered Oct 20 '22 01:10

Kamil Budziewski