C#随笔记03

字符串的声明

必须包含在一对双引号中。

string str=[null];
  • null:如果省略表示str是未初始化的状态。

引用字符串常量

string str1,str2;
str1="我们是学生";
str2="我们是学生";

当两个字符串对象引用相同的常量,就会具有相同的实体。

利用字符数组初始化

char[] charArray={'t','i','m','e'};
string str=new string(charArray);

提取字符数组中的一部分初始化字符串

char[] charArray={'t','i','m','e'};
string str=new string(charArray,1,2);

提取字符串信息

获取字符串长度

string num="123 44 5";
int size=num.Length;

获取指定位置字符

string str="努力加油哦";
char chr=str[4];//将字符串str中索引位置为4的字符赋值给chr
Console.WriteLine("字符串索引位置为4的字符是"+chr);

获取字符串索引位置

IndexOf

返回的是搜索的字符或字符串首次出现的索引位置

public int IndexOf(char value)
public int IndexOf(string value)
public int IndexOf(char value,int startIndex)
public int IndexOf(string value,int startIndex)
public int IndexOf(char value,int startIndex,int count)
public int IndexOf(sting value,int startIndex,int count)
  • value:要搜索的字符
  • startIndex:搜索起始位置
  • count:要检查的字符位置数
  • 返回值:如果找到字符或字符串,则为value的从零开始的索引位置,如果未找到字符或字符串,则为-1
string str="We are friend";
int size-str.IndexOf("e");

查找f在句子中出现的位置

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

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

            string str = "We are friend";
            int firstIndex = str.IndexOf("f");//获取字符串中f第一次出现的索引位置
            int secondIndex = str.IndexOf("f", firstIndex + 1);//获取第二次出现的索引位置
            //输出
            Console.WriteLine("f第一次出现的位置是:" + firstIndex);
            Console.WriteLine("f第二次出现的位置是:" + secondIndex);
            Console.ReadLine();
        }
    }
}

LastIndexOf

public int LastIndexOf(char value)
public int LastIndexOf(string value)
public int LastIndexOf(char value,int startIndex)
public int LastIndexOf(string value,int startIndex)
public int LastIndexOf(char value,int startIndex,int count)
public int LastIndexOf(sting value,int startIndex,int count)

查找e在字符串中最后出现的位置

string str="We are friend";
int size=LastIndexOf('e');

判断字符串首尾内容

  • StartsWith:是否以指定的内容开始
  • EndsWith:是否以指定的内容结束

StartsWith

public bool StartsWith(string value)
public bool StartsWith(string value,bool ignoreCase,CultureInfo culture)
  • value:要比较的字符串
  • ignoreCase:在比较过程中如果忽略大小写,则为true,否则为false
  • culture :cultureInfo对象,用来确定如何对字符串与value进行比较的区域性信息。如果culture为null,则使用当前区域性。
  • 返回值:如果value与字符串的开头匹配则为true,否则为false
string str="梦想还是要有的,万一实现了呢";
bool result=str.StartsWith("梦想");
Console.WriteLine(result);

EndsWith

public bool EndsWith(string value)
public bool EndstWith(string value,bool ignoreCase,CultureInfo culture)
string str="梦想还是要有的,万一实现了呢";
bool result=str.EndsWith("。");
Console.WriteLine(result);

字符串操作

字符串的拼接

使用+运算符可完成对多个字符串的拼接,+运算符可以连接多个字符串并产生一个string对象

比较字符串

  • 关系运算符==
  • Equals:比较两个字符串是否相同
public bool Equals(string value)
public static bool Equals(string a,string b)

如果a和b均为null返回true

验证用户名和密码

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

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

            Console.Write("请输入用户名:");
            string name = Console.ReadLine();
            Console.Write("请输入登录密码:");
            string pwd = Console.ReadLine();
            if (name == "admin" && pwd.Equals("123456"))
            {
                Console.WriteLine("登录成功!");
            }
            else
            {
                Console.WriteLine("输入的用户名或密码错误!!");
            }
            Console.ReadLine();
        }
    }
}

字符串的大小写转换

  • ToUpper
  • ToLower

格式化字符

string类提供了一个静态的Format方法,用于将字符串数据格式化成指定的格式。

public static string Format(string format,Object arg0)
public static string Format(string format,params Object[] arg)
  • format:用来指定字符串所要格式话的形式
{index[,length][:formatString]}
  • index:要设置格式的对象的参数列表中的位置(从0开始)
  • length:参数的字符串表示形式中包含的最小字符数。如果该值是正的,参数右对齐,负的左对齐
  • formatString:要设置格式的对象支持的标准或自定义格式字符串
  • arg():要设置格式的对象
  • arg:一个对象数组,其中包含0个或多个要设置格式的对象
  • 返回值:格式化后的字符串

数值类型数据的格式化

C:货币
D:Decimal
E:指数(科学型)
F:定点
N:Number
P:百分比
X:十六进制
使用string.Format方法对数值类型数据格式化时,传入的参数必须为数值类型

格式化不同的数值类型数据

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

namespace studyDaily
{
    class Program
    {
        static void Main(string[] args)
        {
            //输出金额
            Console.WriteLine(string.Format("1254:{0:C}", 1254));
            //科学计数法
            Console.WriteLine("12000.1:{0:e}", 12000.1);
            //输出以分隔符显示的数据
            Console.WriteLine("128000:{0:N0}", 128000);
            //输出小数点后两位
            Console.WriteLine("Π取小数点后两位:{0:f2}", Math.PI);
            //输出十六进制
            Console.WriteLine("32的十六进制是:{0:X4}", 33);
            //输出百分号数字
            Console.WriteLine("天才是由{0:P0}的灵感加上{1:p0}的汗水", 0.01, 0.9);
            Console.ReadLine();
        }
    }
}

日期时间类型数据的格式化

d:短日期格式
D:长日期格式
f:完整日期时间格式
F:
g:常规日期时间格式
G:
M\m:月/日格式
t:短时间
T:
Y\y:年/月

  • 使用string.Format方法对日期时间类型数据格式话时,传入的参数必须是DataTime类型。

输出不同形式的日期时间

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

namespace studyDaily
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime strDate = DateTime.Now;//获取当前时间
            //输出短日期
            Console.WriteLine(string.Format("{0:d}", strDate));
            //输出长日期
            Console.WriteLine(string.Format("{0:D}", strDate));
            Console.WriteLine();
            //输出完整日期
            Console.WriteLine(string.Format("{0:f}", strDate));
            Console.WriteLine(string.Format("{0:F}", strDate));
            Console.WriteLine();
            //输出时间格式
            Console.WriteLine(string.Format("{0:t}", strDate));
            Console.WriteLine(string.Format("{0:T}", strDate));
            Console.WriteLine();
            //输出月日
            Console.WriteLine(string.Format("{0:M}", strDate));
            //输出年月
            Console.WriteLine(string.Format("{0:Y}", strDate));
            Console.ReadLine();
        }
    }
}

截取字符串

  • Substring
    截取字符串中指定位置和指定长度的子字符串
public string Substring(int startIndex)
public string Substring(int startIndex,int length)
  • startIndex:子字符串的起始位置的索引
  • length:子字符串的字符数
  • 返回值:截取的子字符串

从完整文件名中获取文件名和扩展名

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

namespace studyDaily
{
    class Program
    {
        static void Main(string[] args)
        {
            string strFile = "Program.cs";
            Console.WriteLine("文件完整名称:" + strFile);
            string strFileName = strFile.Substring(0, strFile.IndexOf('.'));//获取文件名
            string strExtension = strFile.Substring(strFile.IndexOf('.'));//获取扩展名
            Console.WriteLine("文件名:" + strFileName);
            Console.WriteLine("扩展名:" + strExtension);
            Console.ReadLine();
        }
    }
}

分割字符串

  • Split
    根据指定的字符数组或字符串数组对字符串进行分割
public string[] Split(params char[] separator)
public string[] Split(char[] separator,int count)
public string[] Split(params char[] separator)
public string[] Split(string[] separator,StringSplitOptions options)
public string[] Split(char[] separator,int count,StringSplitOptions options)
public string[] Split(string[] separator,int count,StringSplitOptions options)
  • separator:分割字符串的字符数组或字符串数组
  • count:要返回的子字符串的最大数量
  • options:要省略返回的数组中的空数组元素,则位RemoveEmptyEntries,要包含返回的数组中的空元素数组则为null
  • 返回值:一个数组,其元素包含分割得到的子字符串,这些子字符串由separator中的一个或多个字符或字符串分割。

分割字符串

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

namespace studyDaily
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "窗前明月光,疑是地上霜,举头望明月,低头思故乡。";
            char[] separator = { ',' };
            string[] splitStrings = str.Split(separator, StringSplitOptions.RemoveEmptyEntries);
            for(int i = 0; i < splitStrings.Length; i++)
            {
                Console.WriteLine(splitStrings[i]);
            }
            Console.ReadLine();
        }
    }
}

去除空白内容

  • Trim
    移除字符串中所有开头空白字符和结尾空白字符
public string Trim()

Trim返回值是从当前字符串的开头和结尾山粗所有空白字符后剩余的字符串。

  • 从字符串开头和结尾删除指定的字符
public string Trim(params char[] trimChars)
char[] charsToTrim={'*'};
string str="*****abc*****";
string shortStr=str.Trim(charsToTrim);

替换字符串

  • Replace
    将字符串中的某个字符或字符串替换成其他的字符或字符串
public string Replace(char Ochar,char Nchar);
public string Replace(string Ovalue,string NValue);

返回值是替换后得到的新字符串

  • 如果要替换的字符或字符串在原字符中重复出现多次,Replace会将所有的都进行替换
string strOld="one world,one dream";
string strNew=strOld.Replace(',','*');

可变字符串类

对于创建成功的string字符串,它的长度是固定的,内容不能被改变和编译。

  • 可变字符序列:StringBuilder类位于System.Text命名空间中,如果要创建StringBuilder对象,首先必须引用该命名空间。
public StringBuilder()
public StringBuilder(int capacity)
public StringBuilder(string value)
public StringBuilder(int capacity,int maxCapacity)
public StringBuilder(string value,int capacity)
public StringBuilder(string value,int startIndex,int length,int capacity)
  • capacity:StringBuilder对象的建议起始大小
  • value:字符串,包含用于初始化StringBuilder对象的子字符串
  • maxCapacity:当前字符串可包含的最大字符数
  • length:子字符串中的字符数

StringBulider类的使用

  • Append:将文本或字符串追加到指定对象的末尾
  • AppendFormat:自定义变量的格式并将这些值追加到StringBuilder对象的末尾
  • Insert:将字符串或对象添加到当前StringBuilder对象中的指定位置
  • Remove:从当前StringBuilder对象中移除指定数量的字符
  • Replace:用另一个指定的字符来替换StringBuilder对象内的字符
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace studyDaily
{
    class Program
    {
        static void Main(string[] args)
        {
            int Num = 234;
            StringBuilder SBuilder = new StringBuilder("小好科技");
            SBuilder.Append("C#练习项目");
            Console.WriteLine(SBuilder);
            SBuilder.AppendFormat("{0:C0}", Num);
            Console.WriteLine(SBuilder);
            SBuilder.Insert(0, "软件");//追加到开头
            Console.WriteLine(SBuilder);
            SBuilder.Remove(10, SBuilder.Length - 10);//删除索引为10以后的字符串
            Console.WriteLine(SBuilder);
            SBuilder.Replace("软件", "开发游戏必会");
            Console.WriteLine(SBuilder);
            Console.ReadLine();
        }
    }
}

null和“”的区别

string str=null;string str="";是两种不同的概念,前者是空对象,没有指向任何引用地址,调用string方法会抛出NullReferenceException空引用异常,而后者是一个字符串,分配了内存空间,可以调用string的任何方法,只是没有显示任何数据而已。

sting类和StingBuilder类的区别

string本身是不可改变的,它只能赋值一次,每一次内容发生改变,都会生成一个新的对象,然后原有的对象引用新的对象。而每一次生成新对象都会对系统性能产生影响。会降低.net编译器的工作效率。
StringBuilder类每次操作都是对自身对象进行操作,而不是生成新的对象,其所占空间会随着内容的增加而扩充。在做大量修改操作时,不会因生成大量匿名对象而影响系统性能。

posted @ 2023-03-07 00:39  flyall  阅读(14)  评论(0)    收藏  举报