Ahmad
Ahmad

Reputation: 335

Determine the middle space of a string and split into 2 strings ASP.NET

I have a string that I am splitting into 2 Strings like this:

string a="Hello World here i am ";
if(a.Length > 10)
{
    string[] result = a.Split(' '); // Divides string into 2 where there is a Space this is type of array 
    string C = result[0]; // This takes the 1st value of that array 
    string D = result[1];);//This takes the  value of that array
    Console.WriteLine(C);
    Console.WriteLine(D);
}

This is a example Console Lines to test real, work I am going to need 2 string to put comments in 2 lines in a comment box.

So this string a could be anything, the problem is I have only 2 lines. I want to split it from the space that is in the middle of this string for example, a code that counts the number of characters such as there in example a.Length > 10 and then find the space that is in the middle of this string in this example it is Hello World here I am here it should see Hello world in one string and here I am into another string any help? I tried looking at alots of examples such as these:

string s = "there is a cat";
//
// Split string on spaces.
// ... This will separate all the words.
//
string[] words = s.Split(' ');
foreach (string word in words)
{
    Console.WriteLine(word);
}

This splits these into couple of lines as well as don't really return 2 strings I want 2 string only. Thanks in Advance

Upvotes: 1

Views: 3299

Answers (1)

Steve
Steve

Reputation: 216323

We can do that with a some IEnumerable extensions like Take and Skip

string a = "This is a long phrase to test the splitting around the middle space";
string[] parts = a.Split(' ');
string first = string.Join(" ", parts.Take(parts.Length / 2));
string second = string.Join(" ", parts.Skip(parts.Length / 2));
Console.WriteLine(first);
Console.WriteLine(second);

However, this is not really the best approach because this method doesn't count the words length and thus you could end with a line a lot shorter than the other.

If you need to have two strings about the same length then you could use a loop like this

string a = "This is a long text to test the splitting around the middle length of the phrase";
string[] parts = a.Split(' ');

int counter = 0;
string first = "";
int middle = a.Length / 2;
while (first.Length < middle)
{
    first += parts[counter] + " ";
    counter++;
}
string second = string.Join(" ", parts.Skip(counter));
Console.WriteLine(first);
Console.WriteLine(second);

Upvotes: 3

Related Questions