zoukankan      html  css  js  c++  java
  • 《C#高级编程》读书笔记(六):字符串和正则表达式

    1,创建字符串

        字符串是一个不可变的数据类型,一旦对字符串对象进行了初始化,该字符串对象就不能改变了。所以,如果用字符串频繁进行文字处理,应用程序就会遇到严重的性能问题,这时需要采用StringBuilder类。

    2,对自定义结构的格式化输出

        实现IFormattable接口

    struct Vector:IFormattable
        {
            public double x, y, z;
    
    
            public Vector(double x, double y, double z) : this()
            {
                this.x = x;
                this.y = y;
                this.z = z;
            }
    
            public Vector(Vector rhs)
            {
                x = rhs.x;
                y = rhs.y;
                z = rhs.z;
            }
    
            public string ToString(string format, IFormatProvider formatProvider)
            {
                if (format == null)
                {
                    return ToString();
                }
    
                switch (format.ToUpper())
                {
                    case "N":
                        return "||" + Norm().ToString() + "||";
                    case "VE":
                        return $"({x:E},{y:E},{z:E})";
                    default:
                        return ToString();
                }
            }
    
            private double Norm()
            {
                return x*x + y*y + z*z;
            }
    
            public override string ToString()
            {
                return "(" + x + "," + y + "," + z + ")";
            }
        }

        测试一下:

    static void Main(string[] args)
            {
                var v1 = new Vector(1,4,-5);
                Console.WriteLine($"{v1,0:N}");
                Console.WriteLine($"{v1,0:VE}");
                Console.WriteLine(v1);
    
                Console.ReadKey();
            }

        输出:    

    ||42||
    (1.000000E+000,4.000000E+000,-5.000000E+000)
    (1,4,-5)

     3,正则表达式

    const string myTest = @"This comprehensive comendium provides a broad and thorough investigation
    of all aspects of programming with ASP.NET.Entirely revised and updated for the fourth release of .NET,this 
    book will give you the information you need to master ASP.NET and build a dynamic,sucessful,enterprise Web 
    application.";
                const string pattern = @"aS*ion";
                MatchCollection myMatches = Regex.Matches(myTest, pattern, RegexOptions.IgnoreCase|
                    RegexOptions.ExplicitCapture);
    
                foreach (Match nextMatch in myMatches)
                {
                    Console.WriteLine(nextMatch.Index);
                }

        

  • 相关阅读:
    快速排序和归并排序的迭代实现
    Longest Increasing Subsequence Review
    IOCCC 1987 最佳单行代码解读
    C++类的成员函数对应的链接器符号的解析
    Scalable Global ID Generator Design
    欧拉回路 (Euler Circuit) POJ 1780
    深入理解函数内静态局部变量初始化
    memcached 线程模型
    类的加载与ClassLoader的理解
    字符集常见码表说明
  • 原文地址:https://www.cnblogs.com/khjian/p/5647792.html
Copyright © 2011-2022 走看看