学习笔记之C#基础知识--String

来源:互联网 发布:sql中怎么设置外键 编辑:程序博客网 时间:2024/06/05 06:55

大多解释来自网络,学习整理。

String 是字符串常量 常量是不可改变的的对象。

StringBuilder是字符串变量,变量是可以被改变的。

例如

string str=“sgc”;

str=str+1;

Console.WriteLine(str);  //输出是sgc1

首先创建对象str并将‘’sgc”赋给str,此时str的值是“sgc”。执行str=str+1;时,新创建了一个对象str并将原来的str的值复制一份再加上“1”赋给了str,所以输出结果为sgc1,但原来的str是没有发生变化的。对字符串的操作是在不停的创建新的字符串对象,所以执行效率较慢。

StringBuilder是字符串变量,是可改变的对象,每当我们用它们对字符串做操作时,实际上是在一个对象上操作的,执行速度就会变快,它是线程非安全的,多数使用在单线程中。

Split()按照指定的字符分割字符串。

using System;

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


namespace String
{
    class String
    {
        static void Main(string[] args)
        {


            //Split字符串分割
            string Str = "s g c l z q q ";
            char[] c = {' '};
            string[] str1 = Str.Split(c);
            foreach(string str2 in str1)
            {
                Console.WriteLine(str2);
                Console.ReadLine();
            }
            StringBuilder sb = new StringBuilder("sgcl");
            Console.WriteLine(sb);
            sb.Append("zqq");//共同占用一块内存,节省了空间
            Console.WriteLine(sb);
            Console.ReadLine();
        }
    }
}
0 0
原创粉丝点击