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();
}
}
运行如下
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。