how to add a space after each four character in string  
Author Message
adorer





PostPosted: .NET Base Class Library, how to add a space after each four character in string Top

is there any way to do that ...

adding something something ( actually space ) after some number of chars in string (actually after four chars in a string)



.NET Development12  
 
 
Mark Dawson





PostPosted: .NET Base Class Library, how to add a space after each four character in string Top

There is not any native method that will let you do that, but the following code should work:

using System;< xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

 

namespace ConsoleApplication1

{

    class Program

    {

        static void Main(string[] args)

        {

            string x = "abcd";

            string y = AddSpaceAtInterval(x, 3);

        }

 

        static string AddSpaceAtInterval(string originalString, int interval)

        {

            if (interval == 0 || (originalString.Length <= interval))

            {

                return originalString;

            }

 

            string newString = String.Empty;

            int currentIndex = 0;

 

            for (int i = 0; i < originalString.Length / interval; ++i)

            {

                newString += originalString.Substring(currentIndex, interval) + " ";

                currentIndex += interval;

            }

 

            if (currentIndex != originalString.Length)

            {

                newString += originalString.Substring(currentIndex, originalString.Length - currentIndex);

            }

 

            return newString;

        }

    }

}

  

If your string is very long or you are going to call this function many times then you may want to use a StringBuilder for better memory perofrmance.

 

Mark.



 
 
Kusala





PostPosted: .NET Base Class Library, how to add a space after each four character in string Top

Here another simple method for you

private string StringModifier(string InputString, int Interval, string InsertString)
{
int i = 1;
int j = 0;

while (true)
{
int NextPos = ((i++) * Interval) + (j++);
if (NextPos > InputString.Length)
break;
else
InputString = InputString.Insert(NextPos, InsertString);
}

return InputString;
}


//Call like this
string MyString = StringModifier("thisthisthisthisthisthisthisthis", 4, " ");


 
 
OmegaMan





PostPosted: .NET Base Class Library, how to add a space after each four character in string Top

Childs play for Regular Expressions see code. Change the 4 in the expression for a different value say to 6 to characters.


using System.Text.RegularExpressions;

public static void AddSpaceAfterFour()
{
string text = "Thisworkwantdocscode1234*&%$";



}




Console OutputThis work want docs code 1234 *&%$