Click here to Skip to main content
15,885,365 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
string value="monobala";

I need to store mono and bala in different variable or in array

What I have tried:

value.split(value.length>2)
I dont know exactly what to do
Posted
Updated 26-Sep-18 2:27am
v3

For even numbered strings its easy:
C#
var MyString = "blabla";
var first = MyString.Substring(0, (int)(MyString.Length / 2));
var last = MyString.Substring((int)(MyString.Length / 2), (int)(MyString.Length / 2));

For odd number strings, you need to make a choise on how to split them.
 
Share this answer
 
v2
Comments
Frank R. Haugen 29-Feb-16 18:53pm    
I'm no expert, but that's not C#, is it?
Kenneth Haugland 29-Feb-16 22:53pm    
Well on VS 2015 it will compile as C#, don't know what you are running on though :laugh:
[no name] 1-Mar-16 0:49am    
+5
I'm really wondering what kind of class you may be in, or what kind of programming task in the real world, could possibly require splitting a string into two parts based on the idea of "half."

However, it's easy to do. Here's one way you could do it:
C#
string bar = "|";
string[] splitStr = new string[] {bar};
string str = "12345678";

string[] byHalf = str.Insert(str.Length / 2, bar).Split(splitStr,StringSplitOptions.RemoveEmptyEntries);
Of course, this method is easily confused if the string you are splitting has the character you use to split it with.

Here's an example using 'StringBuilder for you to study:
C#
string str = "12345678";
StringBuilder sb = new StringBuilder(str);
int half1 = sb.Length/2;
int half2 = sb.Length - half1;
char[] halfOne = new char[half1];
char[] halfTwo = new char[half2];
sb.CopyTo(0, halfOne, 0, half1);
sb.CopyTo(half1, halfTwo, 0, half2);
string[] results = new string[]
{
   new string(halfOne), new string(halfTwo)
};
sb.Clear();
Understand what's going on in each step of this, and you'll learn something that will be useful in the future when you are in a programming scenario where you have to deal with "heavy" string use :)
 
Share this answer
 
Building on @Kenneth Haugland's answer for odd strings (for you lazy folk - like me).

C#
var value = "monobala";
var firstHalfLength = (int)(value.Length / 2);
var secondHalfLength = value.Length - firstHalfLength;
var splitPhone = new[] 
    {
        value.Substring(0, firstHalfLength),
        value.Substring(firstHalfLength, secondHalfLength)
    };
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900