我正在学习一本书中的教程,并且有一小段我不明白的代码。代码如下:
// conv_ex.cs - Exercise 12.4
// This listing will cut the front of the string
// off when it finds a space, comma, or period.
// Letters and other characters will still cause
// bad data.
//-----------------------------------------------
using System;
using System.Text;
class myApp
{
public static void Main()
{
string buff;
int age;
// The following sets up an array of characters used
// to find a break for the Split method.
char[] delim = new char[] { ' ', ',', '.' };
// The following is an array of strings that will
// be used to hold the split strings returned from
// the split method.
string[] nbuff = new string[4];
Console.Write("Enter your age: ");
buff = Console.ReadLine();
// break string up if it is in multiple pieces.
// Exception handling not added
nbuff = buff.Split(delim,2); //<----- what is purpose of (delim,2) in this case?
//nbuff = buff.Split(delim); // will give the same result
//nbuff = buff.Split(delim,3); //will give the same result
// Now convert....
try
{
age = Convert.ToInt32(nbuff[0]);
Console.WriteLine("age is:" + age);
if (age < 21)
Console.WriteLine("You are under 21.");
else
Console.Write("You are 21 or older.");
}
catch (ArgumentException e)
{
Console.WriteLine("No value was entered... (equal to null)");
}
catch (OverflowException e)
{
Console.WriteLine("You entered a number that is too big or too small.");
}
catch (FormatException e)
{
Console.WriteLine("You didn't enter a valid number.");
}
catch (Exception e)
{
Console.WriteLine("Something went wrong with the conversion.");
throw (e);
}
}
}
我的问题是:
“ 2 ”的目的是什么nbuff = buff.Split(delim,2);
?
无论如何,字符串都会分成两半,对吗?
即使没有“ 2 ”,例如nbuff = buff.Split(delim);
结果也是一样的。