具有动态长度的子串

时间:2013-09-25 13:53:23

标签: c# string

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

输入

  

6.3 - 全日托

预期产出:

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

我该怎么做? Substring在这里没有帮助。

5 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分: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);

答案 2 :(得分:0)

这应该有效

var s = "6.3-full-day-care";
var index = s.IndexOf('-');
var price = s.Substring(0, index);
var serviceKey = s.Substring(index + 1);

答案 3 :(得分: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 );

答案 4 :(得分: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];