C#字符串拆分方法

时间:2013-03-08 17:00:38

标签: c# string methods split

我正在阅读一本书中的教程,但有一小段代码我不明白。代码如下:

// 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);
        }
    }
}

我的问题是:

nbuff = buff.Split(delim,2);中“ 2 ”的目的是什么?

无论如何,字符串将分成两半,对吧?

即使没有“ 2 ”,例如nbuff = buff.Split(delim);结果也一样。

4 个答案:

答案 0 :(得分:3)

它指定要返回的最大子串数。

拆分(Char [],Int32)

Returns a string array that contains the substrings in this instance that are delimited by elements of a specified Unicode character array. A parameter specifies the maximum number of substrings to return.

列出here

String.Split()方法有几处重载

答案 1 :(得分:2)

这是返回的最大子串数。将其更改为3的原因没有效果是因为要返回的子字符串少于3个,因此,根据设计,它将返回所有可用的子字符串。例如,如果可能会返回5个子字符串,那么只会返回第一个3

您可以详细了解String.Split()方法here

答案 2 :(得分:2)

2表示要返回的最大字符串数。

有关完整信息,请参阅here

该参数名为 count 。以下是相关文字:

  

如果此实例中有超过 count 个子串,则第一个    count 减去1个子串在第一个计数减1中返回   返回值的元素,以及其中的剩余字符   实例在返回值的最后一个元素中返回。

答案 3 :(得分:1)

2中的buff.Split(delim,2)指定要返回的最大子串数。如果有4个部分用delim中定义的字符分隔的字符串,那么你会注意到一个区别。如果您使用Split(delim,2),则只返回2个子字符串。

您也可以阅读this page on MSDN