我需要将以下字符串的值转换为 2 个变量。
输入
6.3-全日托
预期输出:
var price=6.3; //The input is dynamic.Cannot get fixed length
var serviceKey="full-day-care";
我怎样才能做到这一点?Substring
在这里没有帮助。
您可以使用String.Split
和String.Substring
方法,例如;
string s = "6.3-full-day-care";
int index = s.IndexOf('-'); //This gets index of first '-' character
var price = s.Substring(0, index);
var serviceKey = s.Substring(index + 1);
Console.WriteLine(price);
Console.WriteLine(serviceKey);
输出将是;
6.3
full-day-care
这里一个DEMO
.
你可以这样做:
var val = "6.3-full-day-care";
var index = val.IndexOf("-"); //first occuarance of -
var price =double.Parse(val[index]);
var serviceKey = val.Substring(index);
只是给个主意。最好自然double.TryParse(..)
使用price
double price = 0;
double.TryParse(val[index], out prince, System.Globalization.InvariantCulture);
这应该工作
var s = "6.3-full-day-care";
var index = s.IndexOf('-');
var price = s.Substring(0, index);
var serviceKey = s.Substring(index + 1);
如果价格和密钥总是用“-”分隔:
string s = "6.3-full-day-care";
int separatorIdx = s.IndexOf( '-' ); // get idx of first '-'
// split original string
string price = s.Substring( 0, separatorIdx );
string serviceKey = s.Substring( separatorIdx+1, s.Length );
使用最大计数的 String.Split http://msdn.microsoft.com/en-us/library/c1bs0eda.aspx
string s = "6.3-full-day-care";
string[] parts = s.split(new char[]{'-'}, 1);
var price = parts[0];
var serviceKey = parts[1];