Click here to Skip to main content
15,886,783 members
Please Sign up or sign in to vote.
1.80/5 (2 votes)
See more:
Hi,

I need to format a string.

Source string: 123332qw332w2

Result string: 123-332-qw3-32w2

Is there any easy way to do it as we do for numbers(String.Format)?


Format is not fixed. It is given in the config file like xxx-xxxxx-xxxxx.

That can be stored in some format like xxx-xxxxx-xxx. A group of values take a single format like above.. I need the formatting should be based on a given format like above. Format xxx-xxxxx-xxx will be made configurable. Hope this explains
Posted
Updated 18-Feb-14 17:34pm
v3

See this[^] and this[^]
Regex.Replace[^] might help you out :)

-KR
 
Share this answer
 
try this
C#
public void stringFormat()
       {
           var str = "123332qw332w2";
           var newStr = "";
           var increment = 1;
           for (int index = 3; index < 15; index += (3 + increment))
           {
               newStr = str.Insert(index, "-");
               str = newStr;

           }
             newStr;//final output
       }

It will show your desired output
Happy coding :)
 
Share this answer
 
v2
Comments
ckumaresanmba 18-Feb-14 2:07am    
Some times the format may be different. so i thought to have a generic solution
12-222525-251 or 1245-564-2541
The14thNoah 18-Feb-14 19:27pm    
So the format is not fixed right?
ckumaresanmba 18-Feb-14 23:33pm    
That can be stored in some format like xxx-xxxxx-xxx. A group of values take a single format like above.. I need the formatting should be based on a given format like above. Format xxx-xxxxx-xxx will be made configurable. Hope this explains
The14thNoah 19-Feb-14 0:17am    
ah ok,how many configurable string pattern do you want to use?maybe I can generate method for all the said patterns if I can
astika 18-Feb-14 2:15am    
how to know where to give - in string?
You should use regex.

Refered this link:
http://msdn.microsoft.com/en-us/library/ms972966.aspx[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900