C# 字符串操作详解

1、字符串转字符数组

(1)、ToCharArray()方法,源码如下:

调用代码:

var str = "Hello World";
//将字符串转换成字符数组
var result = str.ToCharArray();
var enumerator = result.GetEnumerator();
while (enumerator.MoveNext())
{
     Console.WriteLine(enumerator.Current);
}

输出结果:

(2)、源码如下:

调用代码如下:

            var str = "Hello World";
            //将字符串转换成字符数组
            var result = str.ToCharArray(2,2);
            var enumerator = result.GetEnumerator();
            while (enumerator.MoveNext())
            {
                Console.WriteLine(enumerator.Current);
            }

输出结果:

(3)、源码如下:

调用代码如下:

            var str = "          Hello World              "; 
            //调用trim方法去除前后的空格
            var result = str.Trim();
            Console.WriteLine("str的原长度:{0},str调用Trim()方法之后的长度{1},结果字符串:{2}",str.Length,result.Length, "$"+ result + "$");

猜你喜欢

转载自www.cnblogs.com/GreenLeaves/p/9101651.html