C# 字符串和正则表达式(8) 持续更新

创建字符串            如果多次修改一个字符串或创建一个很长的字符串,用String类会效率低下。这种情况,可以用 System.Text.StringBuilder ,它专门为这种情况设计的。
格式化表达式          格式化表达式使用两个有效的接口 IFormatProvider 和 IFormattable 。 这样 Console.WriteLine 和 类似的类 以指定的方式显示值。
正则表达式            用 System.Text.RegularExpressions 来识别复杂的字符串

String类

PadLeft、PadRight

string str = "f";
char pad = '.';

Console.WriteLine(str.PadLeft(15, pad));
Console.WriteLine(str.PadLeft(2, pad)); 

输出

..............f
.f
string str = "string string string string string";
str += "addstring addstring addstring";

上面这段代码本身功能很简单,但它如果执行 大量的替换 的操作,如果执行次数越多,性能就越低。

为解决这个这个问题用 StringBuilder。 StringBuidler仅可以替换和追加或删除字符问题。虽然方法少,但它工作方式高效。

 StringBuilder stringBuilder = new StringBuilder("string string string string string",150);
 stringBuilder.AppendLine("addbuilder addbuilder addbuilder addbuilder addbuilder");

StringBuilder 初始容量设置 150 。最好容量设置字符串最大长度,确保StringBuilder不需要重新分配内存。该容量默认设置16。

Console.WriteLine(stringBuilder + "  " + stringBuilder.Capacity );

StringBuilder 只可以用ToString方法 转换为 String, 强制转换是不可以的。

格式化字符串

 double d = 24.123478904523;
 Console.WriteLine("{0,2:F},{1}", d , 12);
 string str = String.Format("{0,2:F},{1}", d, 12);
 Console.WriteLine(str);

其中 2:F 。 F 表示 浮点数 ,2 表示 保留小数点 2位。

还有其他的  https://msdn.microsoft.com/zh-cn/library/dwhawy9k(v=vs.110).aspx

Console.WriteLine 将 参数 传递给 String.Format 输出到控制台。

正则表达式

正则表达式语言 https://msdn.microsoft.com/zh-cn/library/az24scfc(v=vs.110).aspx

private static void Main(string[] args)
{
    Find1();
    Find2();
    Console.ReadLine();
}

private static void Find1()
{
    const string text = @"nion sion naaaion";
    const string pattern = @"nS*ion";
    MatchCollection matches = Regex.Matches(text, pattern,
        RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace |
        RegexOptions.ExplicitCapture);
    WriteMatches(text, matches);
}

private static void Find2()
{
    const string text = @"http://www.baidu.com";
    const string pattern = @"^(http://)(S*)";
    MatchCollection matches = Regex.Matches(text, pattern,
        RegexOptions.IgnoreCase);
    WriteMatches(text, matches);
}

private static void WriteMatches(string text, MatchCollection matches)
{
    Console.WriteLine("matches.Count: " + matches.Count);
    foreach (Match nextMatch in matches)
    {
        int index = nextMatch.Index;
        string result = nextMatch.ToString();
        Console.WriteLine("result:{0}",result);
    }
}
原文地址:https://www.cnblogs.com/z888/p/5799759.html