简体   繁体   中英

How can split string not include first character?

i have some text and split by "-" but i don't want split first character: 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 . 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

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;  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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