using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 字符串的各种方法
{
class Program
{
static void Main(string[] args)
{
求字符串的长度,运用lenghth方法
//string s = "zhang ying qing";
//Console.WriteLine("这个字符串的长度是{0}", s.Length);
//字符串的大小写转换,使用字符串方法toupper与tolower
//问题:比较两个字符串是否相同
// string s1 = "C#";//大写
// //s1 = s1.ToUpper();
// string s2 = "c#";//小写
// //s2 = s2.ToUpper();
if(s1==s2)
//if(s1.Equals(s2,StringComparison.OrdinalIgnoreCase ))
// {
// Console.WriteLine("这两个字符串相同");
// }
// else
// {
// Console.WriteLine("这两个字符串不相同");
// }
// //第二种方法是使用equals方法,equals方法是忽略字符大小写
//字符串的分割,使用的是split方法
//string s = "a b dfr + f = ,,, r";
//char[] chs = { ' ', '+', ',', '=' };//需要删除的字符
//string[] ss = s.Split(chs,StringSplitOptions .RemoveEmptyEntries );//返回值为字符串数组,且不包含空
//判断字符串中是否有关键字用方法contains
//将关键字符串用某个符号替换,使用方法replace
//string str = "国家关键人物老张";
//if(str.Contains("老张"))
//{
// str=str.Replace("老张","***");
//}
//截取字符串substring
//string str = "今天天气好晴朗,处处好风光";
这个字符串的索引是从下标0开始的
str = str.Substring(0);//截取字符串从0开始,包含0
Console.WriteLine(str);
str = str.Substring(1);//截取字符串从1开始,包含1
Console.WriteLine(str);
//str = str.Substring(1,2);//截取字符串从1开始,包含1,两个长度
//Console.WriteLine(str);
判断字符串的开始和结尾,分别用startwith和endwith
//string str = "今天天气好晴朗,处处好风光";
//if(str.StartsWith("今天"))
//{
// Console.WriteLine("yes");
//}
//else
//{
// Console.WriteLine("no");
//}
判断某个字符在字符串中第一次出现的位置,使用方法indexof
//string str = "今天天气好晴朗,处处好风光";
int index = str.IndexOf("天");
//int index = str.IndexOf("天",1);//从起始位置1开始寻找,包含1
//Console.WriteLine(index);
判断字符在字符串中最后一次出现的位置,使用方法lastindexof
//string str = "今天天气好晴朗,处处好风光";
//int index = str.LastIndexOf('天');
//Console.WriteLine(index);
lastindexof与substring的混合使用
//string path = @"c:\a\b\c\d\e\f\r\df\df\es\re\苍老师.wav";
@符号作用是取消\在字符串的转义作用
//int index = path.LastIndexOf("\\");//去最后一个\的位置
//path = path.Substring(index + 1);//从下一个位置截取
//Console.WriteLine(path);
去空字符使用方法trim,去掉前面的空格使用trimstart,去掉后面的空格使用trimend
//string str = " hhhhhhh ";
str = str.Trim();
str = str.TrimStart();
//str = str.TrimEnd();
//Console.Write(str);
判断字符串是否为空,使用方法isnullorempty
//string str = null;
//if(string.IsNullOrEmpty(str))
//{
// Console.WriteLine("yes");
//}
//else
//{
// Console.WriteLine("no");
//}
//分割字符串a|b|c|d,使用的方法为join
string[] names = { "张三", "李四", "王五" };
string strnew = string.Join("|", names);
Console.WriteLine(strnew);
Console.ReadKey();
}
}
}
02字符串的各种方法(02)
最新推荐文章于 2022-09-06 17:07:48 发布