D T
D T

Reputation: 3746

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?

Upvotes: 2

Views: 94

Answers (4)

fubo
fubo

Reputation: 45947

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

Upvotes: 0

Caius Jard
Caius Jard

Reputation: 74605

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;

Upvotes: 3

Tolbxela
Tolbxela

Reputation: 5183

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

Upvotes: 2

Daniel.C. A.
Daniel.C. A.

Reputation: 44

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

Upvotes: 1

Related Questions