c#笔记(P124)——IndexOf() & Substring()

c#代码如下,其中使用了IndexOf和Substring

class Program
    {
        delegate double ProcessDelegate(double param1, double param2);

        static double Multiply(double param1, double param2)
        {
            return param1 * param2;
        }

        static double Divide(double param1, double param2)
        {
            return param1 / param2;
        }

        static void Main(string[] args)
        {
            ProcessDelegate process;
            Console.WriteLine("Enter 2 numbers separated with a comma:");
            string input = Console.ReadLine();
            int commaPos = input.IndexOf(',');//indexof
            double param1 = Convert.ToDouble(input.Substring(0, commaPos));//substring
            double param2 = Convert.ToDouble(input.Substring(commaPos + 1,
                                             input.Length - commaPos - 1));
            Console.WriteLine("Enter M to multiply or D to divide:");
            input = Console.ReadLine();
            if (input == "M")
                process = new ProcessDelegate(Multiply);
            else
                process = new ProcessDelegate(Divide);
            Console.WriteLine("Result: {0}", process(param1, param2));
            Console.ReadKey();
        }
    }

运行如下

  1. 列表内容

IndexOf
含义:取某字符串在源字符串中的索引(索引从0开始)
本例中,源字符串是“7.2,6.3”,“7”的索引是0,“.”的索引是1,“2”的索引是2,“,”的索引是3,以此类推。

int commaPos = input.IndexOf(',')

即为取“,”在源字符串中的索引,结果为3。
若取“6,”在源字符串中的索引,则结果为-1,因为不存在“6,”

Substring
含义:按照索引取字符串中的某一节。
格式:Substring(索引,要取的字符串长度)
本例中,double param1 = Convert.ToDouble(input.Substring(0, commaPos));
是从索引0开始取,要取得字符串长度为commaPos,即为3。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值