简体   繁体   English

拆分字符串如何不包含第一个字符?

[英]How can split string not include first character?

i have some text and split by "-" but i don't want split first character: EX:我有一些文本并用"-" split ,但我不想split第一个字符:EX:

"1-2" => [1,2]
"-1-2" => [-1,2]
"1-2-3" => [1,2,3]
"-1-2-3" => [-1,2,3]

If i use this code, it will all:如果我使用此代码,它将全部:

strValue.Split("-");

How can split string not include first character?拆分字符串如何不包含第一个字符?

Looks to me like you need to split on '-' and if the first entry in the array is empty, then assume that the second entry is a negative number在我看来,您需要在“-”上拆分,如果数组中的第一个条目为空,则假设第二个条目是负数

var x = input.Split('-');
IEnumerable<string> y = x;
if(string.IsNullOrWhiteSpace(x[0])){
  x[1] = "-"+x[1];
  y= x.Skip(1);
}
var z = y.Select(int.Parse).ToArray();

Or flip it after:或者在之后翻转它:

var z = input.Split('-').Select(int.Parse).ToArray();

if(input[0] == '-')
  z[0] *= -1;

My solution is very simple, and without number conversion.我的解决方案很简单,无需数字转换。 Since, in case you have something like "-ab", it does not convert to a number .因为,如果你有类似“-ab”的东西,它不会转换为数字 And the question says about characters in some text.问题是关于某些文本中的字符。

    string[] list;
    if (str.StartsWith("-")) {
        list = str.Substring(1).Split('-');
        list[0]= "-" + list[0];
    } else {
        list = str.Split('-');
    }

Here is a C# Fiddle to play with: https://dotnetfiddle.net/C2qERs这是一个 C# 小提琴: https://dotnetfiddle.net/C2qERs

public string[] Spliting(string toSplit) 
        {
            string[] result=null;

            if (toSplit[0].Equals('-')) 
            {
                result = (toSplit.Substring(1)).Split("-");
                result[0] = "-" + result[0];
            }
            else 
            {
                result = toSplit.Split("-");
            }

            return result;
        }
string input = "-1-2-3";
int[] result = input.Substring(1).Split('-').Select(int.Parse).ToArray(); 
if(input[0] == '-')
    result[0] *= -1;  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM