C# int与string互相转换及数组转换

来源:互联网 发布:数据移植测试 编辑:程序博客网 时间:2024/05/16 10:52

1int-->string

1             int a =15;

2             string s1 = a.ToString();

3             string s2 = Convert.ToString(a);

2string -->int

1             string s ="18";

2             int a1 =int.Parse(s);

3             int a2;

4             int.TryParse(s,out a2);

5             int a3 = Convert.ToInt32(s);

 

总结:

1、可以使用Convertintstring进行来回转化,并且可以指定转化的进制;

2、转化为string,可以使用ToString方法;

3、转化为int,可以使用int.Parse或者int.TryParse方法。

为什么没有string.Parsestring.TryParse方法?不需要,ToString就可以了。

 

c#中从string数组转换到int数组

string[] input = { "1", "2", "3", "4", "5", "6", "7", "8", "9" };
int[] output = Array.ConvertAll<string, int>(input, delegate(string s)

 {

return int.Parse(s);

});

:

使用Array类中的静态泛形式方法ConvertAll进行转换

delegate(string s) { return int.Parse(s); }

这句表示:建立一个匿名委托,该委托关联的方法体是:return int.Parse(s);

将数组中的每个字符串强制转换成整形并返回添加给 output

c#中如何将一个string数组转换为int数组

string[] strArray = "a,b,c,d,e,f,g".Split(new char[]{ ',' });
int[] intArray;

//C# 3.0下用此句
intArray = Array.ConvertAll<string, int>(strArray, s => int.Parse(s));
//2.0下用以下的语句替换上例。
//intArray = Array.ConvertAll<string, int>(strArray, delegate (string s) { return int.Parse(s); } );

C#中List〈string〉和string[]数组之间的相互转换

1,System.String[]转到List<System.String>

System.String[] str={"str","string","abc"};

List<System.String> listS=new List<System.String>(str);

 

2, List<System.String>转到System.String[]

List<System.String> listS=new List<System.String>();

listS.Add("str");

listS.Add("hello");

System.String[] str=listS.ToArray();

 

测试如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            System.String[] sA = { "str","string1","sting2","abc"};
            List<System.String> sL = new List<System.String>();
            for (System.Int32 i = 0; i < sA.Length;i++ )
            {
                Console.WriteLine("sA[{0}]={1}",i,sA[i]);
            }
            sL = new List<System.String>(sA);
            sL.Add("Hello!");
            foreach(System.String s in sL)
            {
                Console.WriteLine(s);
            }
            System.String[] nextString = sL.ToArray();
            Console.WriteLine("The Length of nextString is {0}",nextString.Length);
            Console.Read();
        }
    }
}

0 0
原创粉丝点击