tags:

views:

220

answers:

12

I have a string "8329874566". I want to place - in the string like this "832-98-4566"

Which string function can I use?

+9  A: 

There may be a tricky-almost-unreadable regex solution, but this one is pretty readable, and easy.

The first parameter of the .Substring() method is where you start getting the characters, and the second is the number of characters you want to get, and not giving it sets a default as value.length -1 (get chars until the end of the string):

String value = "8329874566";

String Result = value.Substring(0,3) + "-" + value.Substring(3,2) + "-" + value.Substring(6);

--[edit]--

Just noticed you didn't use one of the numbers AT ALL (number '7') in the expected result example you gave, but if you want it, just change the last substring as "5", and if you want the '7' but don't want 5 numbers in the last set, let it like "5,4".

MarceloRamires
@Marcelo, see my answer.
Joey
Thanks to Johannes Rössel's answer i've seen it's not unreadable at all! just takes some time to understand.
MarceloRamires
A: 
var result = string.Concat(value.Substring(0,3), "-", value.Substring(3,2), "-", value.Substring(5,4));

or

var value = "8329874566".Insert(3, "-").Insert(6, "-");
runrunraygun
A: 

If the hyphens are to go in the same place each time, then you could simply concatenate together the pieces of the orginal string like this:

//               0123456789 <- index
string number = "8329874566";
string new = number.Substring(0, 3) + "-" + number.Substring(3, 2) + "-" + number.Substring(5);

For a general way of making mutable strings, use the StringBuilder class. This allows deletions and insertions to be made before calling ToString to produce the final string.

Paul Ruane
+5  A: 

Are you trying to do this like American Social Security numbers? I.e., with a hyphen after the third and and fifth numerals? If so:

string s = "8329874566";
string t = String.Format("{0}-{1}-{2}", s.Substring(0, 3), s.Substring(3, 2), s.Substring(5));
fatcat1111
A: 

You could try the following:

string strNumber = "8329874566"
string strNewNumber = strNumber.Substring(0,3) + "-" + strNumber.Substring(4,2) + "-" strNumber.Substring(6)

or something in this manner

wintermute
A: 
string val = "832984566";  
string result = String.Format("{0}-{1}-{2}", val.Substring(0,3), val.Substring(3,2), val.Substring(5,4));
ElectricDialect
A: 

A straightforward (but not flexible) approach would be looping over the characters of the string while keeping a counter running. You can then construct a new string character by character. You can add the '-' character after the 3rd and 5th character.

A better approach may be to use a function to insert a single character in the middle of the string at a specific index. String.Insert() would do well. The only thing to pay attention to here is that the string indexes will get off by one with each insert.

EDIT more language-specific as per comments

You mean like string.Insert()? http://msdn.microsoft.com/en-us/library/system.string.insert.aspx
Joey
Yeah. In my original reply, I didn't actually realize what language this was, so my reply is quite general.
+2  A: 

This works fine, and I think that is more clear:

    String value = "8329874566";
    value = value.Insert(3, "-").Insert(6, "-");

The console outputs shows this: 832-98-74566

Javier Morillo
+13  A: 

I would have done something like this..

  string value = "8329874566";
  value = value.Insert(6, "-").Insert(3, "-");
John Kraft
+1. Certainly nicer than fiddling with substrings and trying to keep them consistent.
Joey
Notice that you should insert into the later positions first, so that you don't shift them by inserting into earlier positions first.
Mike Daniels
Nicely done! +1, even though it may be just a typo in the question (the '7' vanishes, which was explained in my answer) you didn't take that in account, but I guess he's going to correct it soon..
MarceloRamires
+6  A: 

Just out of completeness, a regular expression variant:

Regex.Replace(s, @"(\d{3})(\d{2})(\d{4})", "$1-$2-$3");

I consider the Insert variant to be the cleanest, though.

Joey
Joey
@Marcelo: A good reference as well as a point to learn is the site http://regularexpressions.info. Your interpretation here is pretty wrong, actually. The point is that *only* capturing groups (denoted by parentheses [with the exception of `(?...)`]) generate backreferences (which are either `\1` in the regex itself or `$1` in the replacement part [at least for .NET, other flavors may differ]). In your example there is only *one* parenthesized part which is `(3|4)`, which means that there is only `$1` in the replacement; all others are invalid. `[]` or `{}` do not generate backreferences.
Joey
@Marcelo: I found PowerShell also a nice tool for playing around with various parts of .NET. For regular expressions there are the `-match`, `-replace` and `-split` operators which make quick testing of something quite easy.
Joey
+13  A: 

You convert it to a number and then format the string. What I like most about this is it's easier to read/understand what's going on then using a few substring methods.

string str = "832984566";
string val = long.Parse(str).ToString("###-##-####");
Chris Persichetti
+1 I really prefer this way than mine
Javier Morillo
A: 

Now how about this for a general solution?

// uglified code to fit within horizontal limits
public static string InsertAtIndices
(this string original, string insertion, params int[] insertionPoints) {

    var mutable = new StringBuilder(original);

    var validInsertionPoints = insertionPoints
        .Distinct()
        .Where(i => i >= 0 && i < original.Length)
        .OrderByDescending(i => i);

    foreach (int insertionPoint in validInsertionPoints)
        mutable.Insert(insertionPoint, insertion);

    return mutable.ToString();
}

Usage:

string ssn = "832984566".InsertAtIndices("-", 3, 5);

string crazy = "42387542342309856340924803"
    .InsertAtIndices(":", 1, 2, 3, 4, 5, 6, 17, 200, -1, -1, 2, 3, 3, 4);

Console.WriteLine(ssn);
Console.WriteLine(crazy);

Output:

832-98-4566
4:2:3:8:7:5:42342309856:340924803

Overkill? Yeah, maybe...

P.S. Yes, I am regex illiterate--something I hope to rectify someday.

Dan Tao
looks like stackoverflow is ready for F# by thinking mutable is a keyword. Awesome!!
Bryan
@Bryan: Ha, I saw it highlighted there and was like, *What? It compiled for me?* So it's F#, is it? That explains that... (I think it's also telling that SO would be ready to highlight F# properly while still not bothering to fix outstanding problems with VB.NET.)
Dan Tao
Well, the highlighting is abysmal in many circumstances but apparently not important enough to fix as it doesn't generate revenue ;-). As for regexes: Your general solution is certainly clearer than trying to do this with regexes.
Joey