0

我需要将以下字符串的值转换为 2 个变量。

输入

6.3-全日托

预期输出:

var price=6.3; //The input is dynamic.Cannot get fixed length
var serviceKey="full-day-care";

我怎样才能做到这一点?Substring在这里没有帮助。

4

5 回答 5

4

您可以使用String.SplitString.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.

于 2013-09-25T13:58:35.370 回答
2

你可以这样做:

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);
于 2013-09-25T13:56:10.000 回答
0

这应该工作

var s = "6.3-full-day-care";
var index = s.IndexOf('-');
var price = s.Substring(0, index);
var serviceKey = s.Substring(index + 1);
于 2013-09-25T13:59:25.503 回答
0

如果价格和密钥总是用“-”分隔:

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 );
于 2013-09-25T13:59:56.473 回答
0

使用最大计数的 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];
于 2013-09-25T14:20:13.660 回答