【C#】每个程序员都必须知道的字符串方法和属性

目录

1.String类的所有函数

2.字符串的特点

3.字符串应用

3.1StringBuilder应用

3.2字符串常用功能


命名空间:using System;

对字符串的操作是开发中非常常见的,每个程序员都要熟练掌握字符串的使用方法,包括字符串提供的属性、方法等,本文对字符串中常用的方法进行了归纳整理,对比分析,希望对其它程序员所有帮助。

1.String类的所有函数

public static readonly String Empty;
public String(char[] value);
public String(sbyte* value);
public String(char* value);
public String(char c, int count);
public String(char[] value, int startIndex, int length);
public String(sbyte* value, int startIndex, int length);
public String(char* value, int startIndex, int length);
public String(sbyte* value, int startIndex, int length, Encoding enc);
public char this[int index] { get; }
public int Length { get; }
public static int Compare(String strA, String strB);
public static int Compare(String strA, int indexA, String strB, int indexB, int length, bool ignoreCase);
public static int Compare(String strA, int indexA, String strB, int indexB, int length);
public static int Compare(String strA, String strB, bool ignoreCase, CultureInfo culture);
public static int Compare(String strA, String strB, CultureInfo culture, CompareOptions options);
public static int Compare(String strA, String strB, StringComparison comparisonType);
public static int Compare(String strA, String strB, bool ignoreCase);
public static int Compare(String strA, int indexA, String strB, int indexB, int length, StringComparison comparisonType);
public static int Compare(String strA, int indexA, String strB, int indexB, int length, bool ignoreCase, CultureInfo culture);
public static int Compare(String strA, int indexA, String strB, int indexB, int length, CultureInfo culture, CompareOptions options);
public static int CompareOrdinal(String strA, String strB);
public static int CompareOrdinal(String strA, int indexA, String strB, int indexB, int length);
public static String Concat(String str0, String str1, String str2, String str3);
public static String Concat(params String[] values);
public static String Concat(object arg0, object arg1);
public static String Concat(object arg0, object arg1, object arg2);
public static String Concat(object arg0);
public static String Concat(params object[] args);
public static String Concat<T>(IEnumerable<T> values);
public static String Concat(IEnumerable<String> values);
public static String Concat(String str0, String str1);
public static String Concat(object arg0, object arg1, object arg2, object arg3);
public static String Concat(String str0, String str1, String str2);
public static String Copy(String str);
public static bool Equals(String a, String b, StringComparison comparisonType);
public static bool Equals(String a, String b);
public static String Format(IFormatProvider provider, String format, params object[] args);
public static String Format(String format, params object[] args);
public static String Format(String format, object arg0, object arg1, object arg2);
public static String Format(String format, object arg0);
public static String Format(String format, object arg0, object arg1);
public static String Intern(String str);
public static String IsInterned(String str);
public static bool IsNullOrEmpty(String value);
public static bool IsNullOrWhiteSpace(String value);
public static String Join<T>(String separator, IEnumerable<T> values);
public static String Join(String separator, params object[] values);
public static String Join(String separator, params String[] value);
public static String Join(String separator, String[] value, int startIndex, int count);
public static String Join(String separator, IEnumerable<String> values);
public object Clone();
public int CompareTo(object value);
public int CompareTo(String strB);
public bool Contains(String value);
public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count);
public bool EndsWith(String value);
public bool EndsWith(String value, StringComparison comparisonType);
public bool EndsWith(String value, bool ignoreCase, CultureInfo culture);
public bool Equals(String value);
public bool Equals(String value, StringComparison comparisonType);
public override bool Equals(object obj);
public CharEnumerator GetEnumerator();
public override int GetHashCode();
public TypeCode GetTypeCode();
public int IndexOf(String value, int startIndex, int count, StringComparison comparisonType);
public int IndexOf(String value, int startIndex, StringComparison comparisonType);
public int IndexOf(String value, int startIndex, int count);
public int IndexOf(char value, int startIndex, int count);
public int IndexOf(String value);
public int IndexOf(char value, int startIndex);
public int IndexOf(char value);
public int IndexOf(String value, int startIndex);
public int IndexOf(String value, StringComparison comparisonType);
public int IndexOfAny(char[] anyOf, int startIndex);
public int IndexOfAny(char[] anyOf);
public int IndexOfAny(char[] anyOf, int startIndex, int count);
public String Insert(int startIndex, String value);
public bool IsNormalized();
public bool IsNormalized(NormalizationForm normalizationForm);
public int LastIndexOf(String value);
public int LastIndexOf(String value, int startIndex);
public int LastIndexOf(String value, int startIndex, int count);
public int LastIndexOf(String value, StringComparison comparisonType);
public int LastIndexOf(String value, int startIndex, StringComparison comparisonType);
public int LastIndexOf(String value, int startIndex, int count, StringComparison comparisonType);
public int LastIndexOf(char value);
public int LastIndexOf(char value, int startIndex, int count);
public int LastIndexOf(char value, int startIndex);
public int LastIndexOfAny(char[] anyOf);
public int LastIndexOfAny(char[] anyOf, int startIndex, int count);
public int LastIndexOfAny(char[] anyOf, int startIndex);
public String Normalize(NormalizationForm normalizationForm);
public String Normalize();
public String PadLeft(int totalWidth, char paddingChar);
public String PadLeft(int totalWidth);
public String PadRight(int totalWidth, char paddingChar);
public String PadRight(int totalWidth);
public String Remove(int startIndex, int count);
public String Remove(int startIndex);
public String Replace(char oldChar, char newChar);
public String Replace(String oldValue, String newValue);
public String[] Split(char[] separator, int count, StringSplitOptions options);
public String[] Split(String[] separator, StringSplitOptions options);
public String[] Split(String[] separator, int count, StringSplitOptions options);
public String[] Split(char[] separator, int count);
public String[] Split(params char[] separator);
public String[] Split(char[] separator, StringSplitOptions options);
public bool StartsWith(String value, StringComparison comparisonType);
public bool StartsWith(String value, bool ignoreCase, CultureInfo culture);
public bool StartsWith(String value);
public String Substring(int startIndex, int length);
public String Substring(int startIndex);
public char[] ToCharArray();
public char[] ToCharArray(int startIndex, int length);
public String ToLower();
public String ToLower(CultureInfo culture);
public String ToLowerInvariant();
public String ToString(IFormatProvider provider);
public override String ToString();
public String ToUpper(CultureInfo culture);
public String ToUpper();
public String ToUpperInvariant();
public String Trim();
public String Trim(params char[] trimChars);
public String TrimEnd(params char[] trimChars);
public String TrimStart(params char[] trimChars);
public static bool operator ==(String a, String b);
public static bool operator !=(String a, String b);

2.字符串的特点

  • 字符串的存储。字符串是存储在内存中的堆空间,而字符串变量中存储的其实是字符串在堆中的内存地址。
  • 字符串的不可变性。当给字符串重新赋值后,原有的字符串并没有销毁,而是在堆中重新开辟了内存空间,将原有的变量所存的地址重新指向新开辟的内存地址。
  • 字符串的修改。字符串每次修改都要重新开辟空间,耗费时间,因此当存在大量字符串更改操作时可使用StringBuilder(不在内存中反复开辟空间,因此效率非常高)大大提升字符串的执行效率,最后再转换为字符串输出即可。
  • 可以将字符串看做是char类型的一个只读数组。因此可以通过下标去访问字符串中的某一个元素。但不能通过下标为字符串中的元素赋值。若要改变数组中的某个元素,可以将字符串转化为字符数组,更改后再转换为字符串即可实现指定下标元素更改。
  • 字符串的连接+,两边只要有一个是字符串类型,另一个会被自动转换成字符串类型。
  • 一切类型都可以调用.ToString()方法转换成字符串类型。

3.字符串应用

3.1StringBuilder应用

// StringBuilder与string效率对比,SB效率高1000倍多。
// 不使用 StringBuilder,及计时器的使用。
// 总时间:00:00:08.8524931
string s3 = null;
Stopwatch sw1 = new Stopwatch();
sw1.Start();
for (int i = 0; i < 100000; i++) { s3 += i; }
sw1.Stop();
Console.WriteLine(sw1.Elapsed);

// 使用 StringBuilder,及计时器的使用。
// 总时间:00:00:00.0077188
StringBuilder sb = new StringBuilder();
Stopwatch sw2 = new Stopwatch();
sw2.Start();
for (int i = 0; i < 100000; i++) { sb.Append(i); }
sw2.Stop();
Console.WriteLine(sb.ToString());
Console.WriteLine(sw2.Elapsed);

// StringBuilder常用方法
StringBuilder sb1 = new StringBuilder();
sb1.AppendLine("this is 1 line");  // 向sb添加数据,末尾自动加换行符
sb1.Append("this is 2 line");  // 向sb添加数据,末尾不自动加换行符
sb1.Insert(7, " my");  // 向sb插入数据。输出为:this is my 1 line
sb1.Replace("this", "that");  // 替换指定的子串。that is 1 line
Console.WriteLine(sb1.ToString());  // 将sb转化为字符串后才能输出。

3.2字符串常用功能

// 可以将字符串看做是char类型的一个只读数组。
string s1 = "abcdefg";
Console.WriteLine(s1[0]);

// 字符串转化为只读字符数组,再转换为字符串
string s2 = "abcdefg";
char[] chs = s2.ToCharArray();
chs[0] = 'b';
s2 = new string(chs);
Console.WriteLine(s2);

string s4 = "This is english sentences to test";
string s5 = "这是中文测试字符串,你真厉害";

// 获得字符串的长度
int s4len = s4.Length;
Console.WriteLine(s4len.ToString());  // 33

// 将字符串全部转化为小写字母
string s4Lower = s4.ToLower();
Console.WriteLine(s4Lower);  // this is english sentences to test

// 将字符串全部转化为大写字母
string s4Upper = s4.ToUpper();
Console.WriteLine(s4Upper);  // THIS IS ENGLISH SENTENCES TO TEST

// 判断两个字符串是否相等,区分大小写的。
bool s4b1 = s4.Equals(s5); 
Console.WriteLine(s4b1);  //False

// 判断两个字符串是否相等,忽略大小写的。
bool s4b2 = s4.Equals(s5, StringComparison.OrdinalIgnoreCase);
Console.WriteLine(s4b1);  //False

// 字符串输出占位符
// 输出:2018年08月10日
string sData = "2018-08-10";
char[] chs1 = { '-' };
string[] date = sData.Split(chs1, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine("{0}年{1}月{2}日", date[0], date[1], date[2]);

// 分割字符串Split
// 输出:str={"a","b","dfd","fdf"}
string sSplit = "a b   dfd _   +      =  ,,, fdf ";
char[] chs2 = { ' ', '_', '+', '=', ',' };
string[] str = sSplit.Split(chs2,StringSplitOptions.RemoveEmptyEntries);

// 字符串基本操作
string str1= "核心团队成员老孙";
Console.WriteLine(str1.Replace("老孙", "***"));  // 替换字符串内容。输出:核心团队成员***
Console.WriteLine(str1.Substring(2));  // 字符串切片。输出:团队成员老孙
Console.WriteLine(str1.Substring(2,4));  // 字符串切片。输出:团队成员
Console.WriteLine(str1.Contains("老孙")); // 判断字符串是否含有子串。输出:True
Console.WriteLine(str1.StartsWith("老孙"));  // 判断字符串是否以子串开始。输出:False
Console.WriteLine(str1.EndsWith("老孙"));  // 判断字符串是否以子串结尾。输出:True
Console.WriteLine(str1.IndexOf("团队"));  // 子串第一次出现的位置。输出:2
Console.WriteLine(str1.LastIndexOf("成员"));  // 子串最后一次出现的位置。输出:4
Console.WriteLine(string.IsNullOrEmpty(str1));  // 判断字符串是否为空,""和null都是空。输出:False  

// 移除字符串中的空字符
string str2 = "  this is a test.   ";
Console.WriteLine(str2.Trim());  // 移除开始和结尾的空格。输出:this is a test.
Console.WriteLine(str2.TrimEnd());  // 移除结尾的空格。输出:  this is a test.
Console.WriteLine(str2.TrimStart());  // 移除开始的空格。输出:this is a test.   

// 连接字符串
string[] names = { "张三", "李四", "王五" };
string strNew = string.Join("|", names);
Console.WriteLine(strNew);  // 连接字符串。输出:张三|李四|王五

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值