开发者

String manuplation in C#

Is there any method that I can use that returns a fixed length array after spliting a string with some delimiter and fill the rest with a default string. Eg.

string ful开发者_开发技巧lName = "Jhon Doe";
string[] names = fullName.SpecialSplit(some parameters); //This should always return string array of length 3 with the second elememnt set to empty if there is no middle name.


Next time specify the language you're asking about. We're no guessers.

In Java:

fullName.split(" ");

And anyway, no method will "return string array of length 3 with the second elememnt set to empty if there is no middle name". For the method, there are just two elements. You have to write that method yourself wrapping the standard split() method.


You should read over Jon Skeet's Writing the perfect question. It will be beneficial to you in the future when posting questions of StackOverflow.

There is no method in C# to do what you are asking, but you can easily write an extension method to do what I think you are asking.

here is a quick example:

public static class AbreviatorExtention
    {

        public static string[] GetInitials(this String str, char splitChar)
        {
            string[] initialArray = new string[3];
            var nameArray = str.Split(new char[] { splitChar },
                            StringSplitOptions.RemoveEmptyEntries);

            if (nameArray.Length == 2)
            {
                var charArrayFirstName = nameArray[0].ToCharArray();
                var charArrayLastName = nameArray[1].ToCharArray();

                initialArray[0] = charArrayFirstName[0].ToString().ToUpper();
                initialArray[1] = string.Empty;
                initialArray[2] = charArrayLastName[0].ToString().ToUpper();
            }
            else
            {
                for (int i = 0; i < nameArray.Length; i++)
                {
                    initialArray[i] = (nameArray[i].ToCharArray())[1]
                                      .ToString().ToUpper();
                }
            }


            return initialArray;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            string FullName = "john doe";

            //Extension method in use
            string[] names = FullName.GetInitials(' ');

            foreach (var item in names)
            {
                Console.WriteLine(item); 
            }

            Console.ReadLine();
        }
    }

Output:

J

D


I would set it up to split the string separate from the fixed array. If you still want a fixed array, then you set up the array to a size of three an populate. This is not the best method, however, as it has no meaning. Better, set up a person or user class and then populate, via rules, from the split string.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜