views:

185

answers:

4

I am trying to write a function, it has 2 parameters one is of string and another is of number datatype, my function has to place a dot after every N characters, where N is provided at run time (some number provided through number datatype). Can anybody help me out please?

+1  A: 

What language?

In C#:

public string PutDots(string input, int n)
{
    char[] c = input.ToCharArray();
    StringBuilder output = new StringBuilder();
    for (int i = 0; i < c.Length; i++)
    {
        output.Append(c[i]);
        if (i % n == 0 && i > 0) 
        {
            output.Append(".");
        }
    }
    return output.ToString();
}
Terrapin
why i < 0? Are you trying to make him/her think? :)
Chetan Sastry
+2  A: 

This smells like homework, so let me suggest how to start, and then you can come back with how far you've gotten.

First, you need to be able to iterate over the string, or at least to jump forward N characters along its length. Can you think of a construct that allows you to either iterate each character until you've iterated N character, or that allows you to split the string into substrings N characters long?

tpdi
+1  A: 

something like this maybe:

public string foo(string input, int count)
{
  string result = "";
  for(int i=0; i < input.length; i++)
  {
    result += input[i];
    if(i % count == 0)
      result += '.';
  }
  return result;
}

(Depending on the language you might want to use something else then string concatenation to build the resultingstring)

Tjofras
This seems like Java. Be careful. you cannot access each character of the Java String using square brackets with an index like : input[i], as Tjofras as shown. Treat it like a pseudocode.
euphoria83
A: 

In C#:

static string InsertDots(string s, int n)
{
    if(string.IsNullOrEmpty(s)) return s;

    if(n <= 0 || n > s.Length) return s;

    Regex re = new Regex(string.Format("(.{{{0}}})", n));

    return re.Replace(s, "$1.");
}
Chris Doggett