参考书目:C#6.0学习笔记——从第一行C#代码到第一个项目设计(作者周家安)P158
学习目的:掌握string字符串的操作,包括查找字符串增删查改
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Example5_9
{
class Program
{
static void Main(string[] args)
{
//-------整型数值的字符串转换为整形数值------
string intStr = "210";
int convInt = int.Parse(intStr);
Console.WriteLine("将字符串{0}转化为int值:{1}", intStr, convInt);
//-查找字符y 和a的索引,使用IndexOfAny找第一个匹配字符的索引-------
//IndexOfAny找到任意一个字符,返回值就不是-1,
string testStr = "check my app,check my app";
char[] patts = { 'y', 'a' }; //查找的条件
int index1 = testStr.IndexOfAny(patts);
//返回第一个符合查找条件的字符索引
Console.WriteLine("在{0}中查找{1}的索引:{2}", testStr, string.Join(
",", patts), index1);
//Join作用是将数组的元素连接起来
//-查找字符y 和a的索引,使用IndexOfAny找最后一个匹配字符的索引-------
int index2 = testStr.LastIndexOfAny(patts);
Console.WriteLine("在{0}中查找{1}的索引:{2}", testStr, string.Join(
",", patts), index2);
//---------存在性查找---------
//测试字符串"address"中是否包含字符串"re",测试大小写是否敏感
string test_str1 = "address";
string test_str2 = "addRess";
bool result1 = test_str1.Contains("re");
Console.WriteLine("字符串{0}中{1}re", test_str1, result1 ? "包含" : "不包含");
bool result2 = test_str2.Contains("re");
Console.WriteLine("字符串{0}中{1}re", test_str2, result2 ? "包含" : "不包含");
//答案是大小写敏感
//-------判断是否是字符串"address"中以ad开头-----
bool result3 = test_str1.StartsWith("ad");
Console.WriteLine("字符串{0}中{1}以ad开头", test_str1, result3 ? "是" : "不是");
//----------字符串中添加新字符------
string test_str4 = "大家好";
string resultStr4 = test_str4.Insert(2, "晚上");
Console.WriteLine("在字符串“{0}”中插入新字符“{1}”后的字符串为:“{2}”",
test_str4, "晚上", resultStr4);
testStr = "山重水复";
// 删除字符
string resultStr = testStr.Remove(1, 1).Remove(2, 1);
Console.Write("去掉“{0}”中的“重”和“复”:{1}\n", testStr, resultStr);
testStr = "bag";
// 替换字符
resultStr = testStr.Replace("b", "fl");
Console.Write("将“{0}”中的“b”替换为“fl”:{1}\n", testStr, resultStr);
testStr = " name ";
// 去掉首尾的空格
resultStr = testStr.Trim();
Console.WriteLine("去掉“{0}”中首尾的空格:{1}", testStr, resultStr);
Console.ReadKey();
}
}
}
运行结果如下: