[英]How can split string not include first character?
我有一些文本並用"-"
split
,但我不想split
第一個字符:EX:
"1-2" => [1,2]
"-1-2" => [-1,2]
"1-2-3" => [1,2,3]
"-1-2-3" => [-1,2,3]
如果我使用此代碼,它將全部:
strValue.Split("-");
拆分字符串如何不包含第一個字符?
在我看來,您需要在“-”上拆分,如果數組中的第一個條目為空,則假設第二個條目是負數
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();
或者在之后翻轉它:
var z = input.Split('-').Select(int.Parse).ToArray();
if(input[0] == '-')
z[0] *= -1;
我的解決方案很簡單,無需數字轉換。 因為,如果你有類似“-ab”的東西,它不會轉換為數字。 問題是關於某些文本中的字符。
string[] list;
if (str.StartsWith("-")) {
list = str.Substring(1).Split('-');
list[0]= "-" + list[0];
} else {
list = str.Split('-');
}
這是一個 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.