0

我如何修剪和转换字符串如下:

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
4

3 回答 3

5

尝试使用以下代码:

            string str = "15k34";
            int val;
            if (str.Length>1)
            {
                if (int.TryParse(str.Substring(0, 2), out val))
                {
                    //val contains the integer value
                }

            }
于 2012-06-24T06:41:26.407 回答
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;
    }
}
于 2012-06-24T06:37:13.243 回答
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

于 2012-06-24T06:45:08.180 回答