我如何修剪和转换字符串如下:
string abc = "15k34"
int x = first two characters of abc // should be 15
but if abc begins with "0"
for example - string abc = "05k34"
int x = first two characters of abc // should be 5
答案 0 :(得分:5)
尝试使用以下代码:
string str = "15k34";
int val;
if (str.Length>1)
{
if (int.TryParse(str.Substring(0, 2), out val))
{
//val contains the integer value
}
}
答案 1 :(得分:2)
string abc = "15k34";
int x = 0;
//abc = "05k34";
int val;
if (!string.IsNullOrEmpty(abc) && abc.Length > 1)
{
bool isNum = int.TryParse(str.Substring(0, 2), out val);
if (isNum)
{
x = val;
}
}
答案 2 :(得分:1)
我认为从伪代码中你通常会有数字,其中'k'代表数千。
因此...
string abc = "15k34";
string[] numbers = abc.Split('k'); //This will return a array { "15", "34" }
int myInt = Convert.ToInt32(numbers[0]);
如果字符串为“05k34”,则myInt的值将为5。
文件:
http://msdn.microsoft.com/en-us/library/1bwe3zdy
http://msdn.microsoft.com/en-us/library/bb397679.aspx