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.
|