简体   繁体   中英

Substring with dynamic length

I need to get value of below string into 2 variables.

Input

6.3-full-day-care

Expected output:

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

How can I do that? Substring doesn't help here.

You can use String.Split and String.Substring methods like;

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

Output will be;

6.3
full-day-care

Here a DEMO .

you can do like:

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

Just to give idea. It's beter naturally use double.TryParse(..) on price

double price = 0; 
double.TryParse(val[index], out prince, System.Globalization.InvariantCulture);

This should work

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

If the price and the key are always separated with a '-':

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

Use String.Split with a maximum count 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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM