user1681820
user1681820

Reputation: 21

How to split a string and store in different string array

if i have a string like

string hello="HelloworldHellofriendsHelloPeople";

i would like to store this in a string like this

Helloworld
Hellofriends
HelloPeople

It has to change the line when it finds the string "hello"

thanks

Upvotes: 1

Views: 8019

Answers (5)

Anirudha
Anirudha

Reputation: 32817

You can use this regex

(?=Hello)

and then split the string using regex's split method!

Your code would be:

      String matchpattern = @"(?=Hello)";
      Regex re = new Regex(matchpattern); 
      String[] splitarray = re.Split(sourcestring);

Upvotes: 2

cuongle
cuongle

Reputation: 75316

 var result = hello.Split(new[] { "Hello" }, 
                    StringSplitOptions.RemoveEmptyEntries)
               .Select(s => "Hello" + s);

Upvotes: 4

Dave Zych
Dave Zych

Reputation: 21897

You could use string.split to split on the word "Hello", and then append "Hello" back onto the string.

string[] helloArray = string.split("Hello");
foreach(string hello in helloArray)
{
    hello = "Hello" + hello;
}

That will give the output you want of

Helloworld
Hellofriends
HelloPeople

Upvotes: 0

D'Arcy Rittich
D'Arcy Rittich

Reputation: 171559

string hello = "HelloworldHellofriendsHelloPeople";
var a = hello.Split(new string[] { "Hello"}, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in a)
    Console.WriteLine("Hello" + s);

Upvotes: 6

Aghilas Yakoub
Aghilas Yakoub

Reputation: 29000

You can use this code - based on string.Replace

var replace = hello.Replace( "Hello", "-Hello" );
var result = replace.Split("-");

Upvotes: 0

Related Questions