Home > Software engineering >  How can split string not include first character?
How can split string not include first character?

Time:12-22

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?

CodePudding user response:

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;

CodePudding user response:

My solution is very simple, and without number conversion. Since, in case you have something like "-a-b", 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

CodePudding user response:

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

CodePudding user response:

string input = "-1-2-3";
int[] result = input.Substring(1).Split('-').Select(int.Parse).ToArray(); 
if(input[0] == '-')
    result[0] *= -1;  
  •  Tags:  
  • c#
  • Related