我如何将我的字符串分成相等的一半并将其存储在变量中 [英] How do i split my string in equal half and store that in variable

查看:100
本文介绍了我如何将我的字符串分成相等的一半并将其存储在变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

string value =monobala;



我需要将mono和bala存储在不同的变量或数组中



我尝试过:



value.split(value.length> 2)

我不确切知道该做什么

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

推荐答案

对于偶数编号的字符串,它很容易:

For even numbered strings its easy:
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.


我是真的想知道你可能在哪个班级,或者现实世界中的什么样的编程任务,可能需要根据一半的想法将字符串分成两部分。



但是,这很容易做到。这是你可以做到的一种方法:
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:
string bar = "|";
string[] splitStr = new string[] {bar};
string str = "12345678";

string[] byHalf = str.Insert(str.Length / 2, bar).Split(splitStr,StringSplitOptions.RemoveEmptyEntries);

当然,如果你要拆分的字符串有你用来拆分的字符,这个方法很容易混淆。



这是一个使用'StringBuilder供你学习的例子:

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:

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 :)


建立在 @Kenneth Haugland 的奇数字符串的答案(为你懒惰的人 - 和我一样)。



Building on @Kenneth Haugland's answer for odd strings (for you lazy folk - like me).

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)
    };


这篇关于我如何将我的字符串分成相等的一半并将其存储在变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆