Click here to Skip to main content
Click here to Skip to main content

Advanced String Split and Joiner

By , 11 Nov 2012
 

Introduction

Basically string has functions to split and join,

But using this will have some problems

  1. You need to find one splitting character which user should not give,
  2. You should provide extra validation logic for preventing that input,
  3. For some cases input are going to be dynamic and you can’t restrict.

And this restriction will create discomfort to the users to.

To come out of this problem I had developed two new functions called SplitAdv and JoinAdv.

This is used to split and join the string. It is useful if you have splitting characters in a string.

Background

Let's say you have a string values as:

string a ="a,b", b ="1,2,", c="@,&,z$^", d= "fhgvh";

You want to join this string values using separator ",". The default string join will not work. But this advanced joiner will work.

public void TestMethod()
{
    string a = "a,b", b = "1,2,", c = "@,&,z$^", d = "fhgvh";

    string stringJoined = StringSplitJoiner.Join(",", a, b, c, d);

    List<string> split = stringJoined.SplitAdv(",");

    Assert.AreEqual(a + b + c + d, split[0] + split[1] + split[2] + split[3]);
}

Using Source code

using System;
using System.Collections.Generic;
using System.Text;

namespace String.Split.Joiner
{
    public static class StringSplitJoiner
    {
        /// <summary>
        /// Joins the specified separator.
        /// Joins the adv.
        /// </summary>
        /// <param name="separator">The separator.</param>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public static string JoinAdv(this string[] value, string separator)
        {
            return StringSplitJoiner.Join(separator, value);
        }

        /// <summary>
        /// Splits the specified content.
        /// Splits the adv.
        /// </summary>
        /// <param name="Content">The content.</param>
        /// <param name="separator">The separator.</param>
        /// <returns></returns>
        public static List<string> SplitAdv(this string Content, string separator)
        {
            return StringSplitJoiner.Split(Content, separator);
        }

        /// <summary>
        /// Joins the specified separator.
        /// </summary>
        /// <param name="separator">The separator.</param>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public static string Join(string separator, params string[] value)
        {
            StringBuilder joinValue = new StringBuilder();
            for (int i = 0; i < value.Length; i++)
            {
                joinValue.Append(value[i].Replace(separator, separator + separator) + separator);
            }
            return joinValue.ToString().TrimEnd(',');
        }

        /// <summary>
        /// Splits the specified content.
        /// </summary>
        /// <param name="Content">The content.</param>
        /// <param name="separator">The separator.</param>
        /// <returns></returns>
        public static List<string> Split(string Content, string separator)
        {
            
            Console.WriteLine("Input String is :");
            Console.WriteLine(Content);
            Console.WriteLine();
            Console.WriteLine("split char String : " + separator);
            Console.WriteLine();

            List<string> SplittedString = new List<string>();
            while (Content.Contains(separator))
            {
                int stringIndexOf = Content.IndexOf(separator);

                while (stringIndexOf != -1 &&
                    ((substring(Content, stringIndexOf + separator.Length, separator) == separator) ||/*Next Char*/
                   substring(Content, stringIndexOf - separator.Length, separator) == separator))/*previous Char */
                {
                    if (separator.Length == 1 &&
                      substring(Content, stringIndexOf + separator.Length, separator) != separator)/*Next Char*/
                    {
                        int tempValue = splitCharLength(Content, stringIndexOf, separator);

                        if (tempValue % 2 == 0)
                            break;
                    }

                    stringIndexOf += separator.Length;

                    stringIndexOf = Content.IndexOf(separator, stringIndexOf);

                }

                if (stringIndexOf == -1)
                {
                    stringIndexOf = Content.Length;
                }

                addString(SplittedString, Content.Substring(0, stringIndexOf), separator);

                if (stringIndexOf == Content.Length)
                {
                    break;
                }

                Content = Content.Substring(stringIndexOf + separator.Length);

                if (Content.Contains(separator) == false)
                {
                    addString(SplittedString, Content, separator);
                }
            }

            if (SplittedString.Count == 0)
            {
                addString(SplittedString, Content, separator);
            }

            for (int i = 0; i < SplittedString.Count; i++)
            {
                System.Console.WriteLine(SplittedString[i]);
            }

            return SplittedString;
        }

        #region * Helper Functions

        /// <summary>
        /// Adds the string to the list.
        /// </summary>
        /// <param name="SplittedString">The splitted string.</param>
        /// <param name="Content">The content.</param>
        /// <param name="separator">The separator.</param>
        private static void addString(List<string> SplittedString, string Content, string separator)
        {
            SplittedString.Add(Content.Replace(separator + separator, separator));
        }

        /// <summary>
        /// Splits the length of the char.
        /// </summary>
        /// <param name="Content">The content.</param>
        /// <param name="startIndex">The start index.</param>
        /// <param name="separator">The separator.</param>
        /// <returns></returns>
        private static int splitCharLength(string Content, int startIndex, string separator)
        {
            int index = 0;
            while (startIndex != 0 && Content[--startIndex].ToString() == separator)
            {
                index++;
            }
            return index;
        }

        /// <summary>
        /// Substrings the specified content.
        /// </summary>
        /// <param name="Content">The content.</param>
        /// <param name="stringIndexOf">The string index of.</param>
        /// <param name="separator">The separator.</param>
        /// <returns></returns>
        private static string substring(string Content, int stringIndexOf, string separator)
        {
            if (Content.Length <= stringIndexOf)
                return "";

            if (stringIndexOf <= -1)
                return "";

            return Content.Substring(stringIndexOf, separator.Length);
        }

        #endregion
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Bala.effie
Web Developer
India India
Member
Hi this is Balaji from India, presently working as a Sr Software Developer in asp.net
using c#.
 
I am interested in sharing information among peoples, I believe this is one the way to spread and get more ideas.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionWhy not going vor XML Serialization?memberAndreas Gieriet11 Nov '12 - 6:55 
AnswerRe: Why not going vor XML Serialization?memberBala.effie11 Nov '12 - 16:05 
Question[My vote of 2] This is not an article - far too little contentmemberAndreas Gieriet10 Nov '12 - 13:05 
QuestionReposted...mvpDave Kreskowiak10 Nov '12 - 4:47 
I see you reposted the "article", but you still haven't fixed any of the problems mentioned before.
 
This includes specifying that the problem you're solving is an "edge case" or functionality that you specifically need for your data. This is NOT an indicator that Join or Split is broken.
 
You also do not go into the design of your solution and how the code works. Code comments do NOT count toward this. Remove the code snippets and read what's left. The article text should stand on its own to discuss the topic entirely. Yours doesn't pass that test.
 
Also, your code creates lots of little String objects. You can get better performance and not give the GC such a workout by redesigning these methods to use StringBuilder instead.

GeneralMy vote of 5membervsmukesh9 Nov '12 - 18:17 
GeneralRe: My vote of 5mvpDave Kreskowiak10 Nov '12 - 4:48 
GeneralRe: My vote of 5memberAndreas Gieriet10 Nov '12 - 10:09 
QuestionSome good work, some bad pointsmemberJohn Brett8 Nov '12 - 23:03 
General[My vote of 2] string.Join DOES workmemberMatt T Heffron8 Nov '12 - 7:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 11 Nov 2012
Article Copyright 2012 by Bala.effie
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid