C#_字符串的操作
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Text;
5: using System.Threading.Tasks;
6: 7: namespace FunWithStrings
8: {9: class Program
10: {11: //基本操作
12: static void BasicStringFunctionality()
13: {14: Console.WriteLine("Basic String Functionality:");
15: string str = "VisualStudio2013";
16: Console.WriteLine("Value of str:{0}", str);
17: Console.WriteLine("str has {0} characters.", str.Length); //获取长度
18: Console.WriteLine("str in uppercase:{0}", str.ToUpper()); //转成大写
19: Console.WriteLine("str in lowercase:{0}", str.ToLower()); //转成小写
20: Console.WriteLine("str contains the letter 2013 ? :{0}", str.Contains("2013")); //判断是否包含"2013"
21: Console.WriteLine("str after replace : {0}",str.Replace("2013","")); //将2013 替换掉
22: Console.ReadKey(); 23: }24: //拼接字符串
25: static void StringConcatenation()
26: {27: //使用“+”拼接字符串
28: Console.WriteLine("String concatenation:");
29: string str1 = "字符串";
30: string str2 = "拼接";
31: string str3 = str1 + str2;
32: Console.WriteLine(str3); 33: Console.ReadKey();34: //使用String.Concat()拼接
35: Console.WriteLine("String concatenation:");
36: string str4 = "世界杯";
37: string str5 = "比赛";
38: string str6 = String.Concat(str4, str5);
39: Console.WriteLine(str6); 40: Console.ReadKey(); 41: 42: }43: //给字符串转义
44: static void EscapeChars()
45: {46: Console.WriteLine("Escape character:\a");
47: string stringWithTabs = "this\tis\ta\tdemo\t!";
48: Console.WriteLine(stringWithTabs);49: Console.WriteLine("\"Hello Wolrd!\"");
50: Console.WriteLine("C:\\Windows\\System32\\drivers\\etc");
51: //使用逐字字符串
52: Console.WriteLine(@"D:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7");
53: //使用逐字字符串保留空格
54: string longString = @"
55: 春江潮水连海平,海上明月共潮生。 56: 滟滟随波千万里,何处春江无月明! 57: 江流宛转绕芳甸,月照花林皆似霰; 58: 空里流霜不觉飞,汀上白沙看不见。 59: 江天一色无纤尘,皎皎空中孤月轮。 60: 江畔何人初见月?江月何年初照人? 61: 人生代代无穷已,江月年年只相似。"; 62: Console.WriteLine(longString); 63: Console.ReadKey(); 64: }65: //相等性测试
66: static void StringWquality()
67: {68: Console.WriteLine("字符串相等测试");
69: string str1 = "Hello";
70: string str2 = "World";
71: Console.WriteLine("str1={0}", str1);
72: Console.WriteLine("str2={0}", str2);
73: Console.WriteLine("str1=str2:{0}", str1 = str2);
74: Console.WriteLine("str1=Hello:{0}", str1 == "Hello");
75: Console.WriteLine("str1=HELLO:{0}", str1 == "HELLO");
76: Console.WriteLine("str1.Equals(str2):{0}", str1.Equals(str2));
77: Console.WriteLine("Hello.Equals(str2):{0}", "Hello".Equals(str2));
78: Console.ReadKey(); 79: }80: static void Main(string[] args)
81: { 82: BasicStringFunctionality(); 83: StringConcatenation(); 84: EscapeChars(); 85: StringWquality(); 86: } 87: } 88: }运行效果

浙公网安备 33010602011771号