一、字符串及常用方法
在 C# 语言中提供了对字符串类型数据操作的方法,例如截取字符串中的内容、查找字符串
中的内容等。
常用的字符串操作包括获取字符串的长度、查找某个字符在字符串中的位置、替换字符串中
的内容、拆分字符串等。
在字符串操作中常用的属性或方法如下表所示:
注意:C#中的字符串虽然是引用类型,但其所有方法都返回的是新的对象。
二、获取字符串长度
字符串实际上是由多个字符组成的,字符串中的第一个字符使用字符串[0]即可得。[0]中的0 称为下标。
获取字符串中的第一个字符使用的下标是 0,则字符串中最后一个字符的下标是字符串的长度减 1。
举例如下:
class Program
{
static void Main(string[] args)
{
string str = Console.ReadLine();
Console.WriteLine("字符串的长度为:" + str.Length);
Console.WriteLine("字符串中第一个字符为:" + str[0]);
Console.WriteLine("字符串中最后一个字符为:" + str[str.Length ‐ 1]);
}
}
三、查找字符串中的字符
在字符串中查找是否含有某个字符串是常见的一个应用,例如在输入的字符串中查找特殊字符、获取某个字符串在原字符串中的位置等。
在 C# 中字符串的查找方法有 IndexOf、LastlndexOf。
IndexOf 方法得到的是指定字符串在原字符串中第一次出现的位置。LastlndexOf 方法得到的是指定字符串在查找的字符串中最后一次出现的位置。
举例如下:
class Program
{
static void Main(string[] args)
{
string str = Console.ReadLine();
if (str.IndexOf("@") != ‐1)
{
Console.WriteLine("字符串中含有@,其出现的位置是{0}", str.IndexOf("@") + 1);
}
else
{
Console.WriteLine("字符串中不含有@");
}
}
}
四、字符串替换方法
字符串的替换操作是指将字符串中指定的字符串替换成新字符串。
在 C# 中替换字符串的方法是Replace方法。
举例如下:
class Program
{
static void Main(string[] args)
{
string str = Console.ReadLine();6 if (str.IndexOf(",") != ‐1)
{
str = str.Replace(",", "_");
}
Console.WriteLine("替换后的字符串为:" + str);
}
}
五、字符串截取函数
截取字符串的方法是 Substring 方法。
在使用该方法时有以下两种方法传递参数:
Substring(指定位置); //从字符串中的指定位置开始截取到字符串结束
Substring(指定位置, 截取的字符的个数); //从字符串中的指定位置开始截取指定字符个数的字符
举例如下:
class Program
{
static void Main(string[] args)
{
string str = Console.ReadLine();
int firstIndex = str.IndexOf("@");
int lastIndex = str.LastIndexOf("@");
if(firstIndex != ‐1 && firstIndex == lastIndex)
{
str = str.Substring(0, firstIndex);
}
Console.WriteLine("邮箱中的用户名是:" + str);
}
}
六、字符串插入
在一个字符串中可以在指定位置插入另一个字符串。插入字符串使用的方法是 Insert 方法。
在 Insert 方法中需要两个参数,一个是字符串插入的位置,一个是字符串。举例如下:
class Program
{
static void Main(string[] args)
{
string str = Console.ReadLine();
//在第二个字符位置插入
str = str.Insert(1, "Test");
Console.WriteLine("新字符串为:" + str);
}
}