“开发一个项目就是不断地去处理字符串”----酒精沙场的程序员如是说
字符串的特点:
1.字符串是引用类型(相对于值类型)
其数据存储在堆空间,在栈空间中存储改数据的地址。
我们熟知的数值变量是值类型,其值存储在栈空间。
2.字符串不可变
当给字符串赋值时,旧值并未销毁,而是重新开辟新的空间来存储
3.字符串可以看做是数组
使用字符串变量【下标】的形式可以读取指定字符,也可使用for循环变量数组
字符串.Length,也可以获得字符个数
本篇包含:
字符串基础:
概念
拼接成的文本值,有点像数组可单个元素(字符)操作
声明
string str = [null]; //声明
string strname; //声明
初始化
对声明好的字符串进行赋值
方法一:直接用字符串进行赋值
// 声明同时初始化
string a = "实践是检验真理的唯一标准";
string b = "锄禾日当午";
// 先声明,再初始化
string str1;
string str2;
str1 = "we are students";
str2 = "we are students";
注意:当两个变量引用相同的内容时,如上面的str1与str2。他们指向相同的内存空间
方法二:利用字符数组初始化
char[] charArray = {'t','i','m','e'}; //定义一个字符数组,数组里的每个元素都是字符
string str = new string (charArray); //将这个字符数组整体转换为字符串str = “time”
//提取字符数组中的一部分转化为字符串
char[] charArray = {'t','i','m','e'}; //定义一个字符数组,数组里的每个元素都是字符
string str = new string (charArray,1,2); //从1号位置元素开始,共向后取2个元素
// str = “im”
提取字符串信息:
1.获取长度
使用string类的length属性获取实例对象的字符串长度
语法格式:
public int Length { get;}
实例:
string num = "12345 6789";
int size = num.Length; //获取字符串长度
2.获取指定位置的字符
string = str = "0123456";
char a = str[5]; // 获取字符串中单个字符-与Python相同语法
3.获取子字符串的索引位置
我们使用string类中的Indexof方法与LastIndexof方法
Indexof方法:返回搜索字符(字符串)首次出现的位置
语法:
// public int Indexof(待检索的字符(字符串))
public int Indexof(char value)
public int Indexof(string value)
//public int Indexof(待检索的字符(字符串),检查开始位置)
public int Indexof(char value,int startIndex)
public int Indexof(string value,int startIndex)
//public int Indexof(待检索的字符(字符串),检查开始位置,检查的字符数量)
public int Indexof(char value,int startIndex,int count)
public int Indexof(string value,int startIndex,int count)
实例:
string str = "we are students";
int size = str.Indexof('e'); //size = 1
int size = str.Indexof('e',2); //size = 5
LastIndexof方法:返回搜索字符(字符串)最后出现的位置
语法:
// 从最后位置开始搜索字符(字符串)位置
public int LastIndexof(char value)
public int LastIndexof(string value)
// public int LastIndexof(待查字符(串),起始查找位置--往前找不是往后找)
public int LastIndexof(char value,int startLastIndexof)
public int LastIndexof(string value,int startLastIndexof)
// public int LastIndexof(待查字符(串),起始查找位置--往前找不是往后找,查找个数--往前数几个)
public int LastIndexof(char value,int startLastIndexof,int count)
public int LastIndexof(string value,int startLastIndexof,int count)
实例:
string a = “we are stude”;
int b = a.LastIndexof('e'); //b=15
int b = a.LastIndexof('e',10); //b=8
int b = a.LastIndexof('e',8,2); //b=-1(未找到该值)
4.判断字符串首尾内容
string类使用StartsWIth方法和EndsWith方法对首尾字符串内容进行判断,返回 true或false
StartsWIth方法:判断字符串是否以指定内容开头
语法:
public boo