String manipulation

Hello

I have a string and a 'variable' length. I want to divide the string into the specified length and store it in an array.

For ex: string = "Experts Exchanges"  and length = 4;

the ArrayList Should contain:
Expe
rts
Exch
ange
s

How can I do this?

Thanks
Praveen
praveenuniAsked:
Who is Participating?
 
cookreCommented:
idx=0;
while (s.Length>4)
         {
         arr[idx++]=s.Substring(0,4);
         s=s.Substring(4);
         }
if (s.Length>0) arr[idx]=s;
0
 
pbowensCommented:
You could also do the same thing with regex..

using System.Text.RegularExpressions;

string test = "Welcome to the experts exchange";

Regex re = new Regex(".{4}");
foreach (Match m in re.Matches(test))
{
   Console.WriteLine(m.ToString());
}
0
 
dunglaCommented:
based on cookre solution:

string strEE = "Experts Exchanges";
ArrayList arrOut = new ArrayList();
while (strEE.Length > 4)
{
      arrOut.Add(strEE.Substring(0, 4));
      strEE = strEE.Substring(4);
}
if (strEE.Length > 0)
      arrOut.Add(strEE);
for (int i = 0; i < arrOut.Count; i++)
{
      Console.WriteLine(arrOut[i]);
}
Console.ReadLine();
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.