Question

Formatting a String in C#

Asked by: Tony_k

I want to write a property in C# to test the format of a string called Vcode:
The following format are valid: M1M1M1, M1M M1M(for this one I I have to create a function to eliminate the space between M1M and M1M), M1M-M1M (for this one I have to eliminate the dash - and make it like M1M1M1)
and this property will be valid for the above and not valid for the format below:
 // Not Valid: M1M1M1A, M1M-M1MA, 73120, MMM-111

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-10-23 at 17:01:40ID24839766
Tags

Formatting a string in C#

Topics

CodeForge

,

C# Programming Language

,

Microsoft Visual C#.Net

Participating Experts
3
Points
500
Comments
17

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Eliminate spacing in a string
    How do i eliminate spacing in a string.
  2. Adding a dash to a string.
    I need to format a string to display a dash ("-) in between the third and fourth digits. Example "1234" to "123-4". How do I format/convert the string to add the dash?

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: jamesrhPosted on 2009-10-23 at 18:04:50ID: 25650208

are you trying to create a function or a property in a class?  M represents? and 1?
you can use a combination of regular expression and string replace to achieve the result.  I can give you more specific info once I know the answers to above.

 

by: x77Posted on 2009-10-23 at 18:49:22ID: 25650373

I also use Functions / Property to validate data.
Two reasons:

  • Regular exprexsions are cryptic, no debugable, No documentable. 
  • Functions / Property can raise exceptions especific for each error. 


To develop the validation code, I use states. This simplifies a lot the code.

The sample code is ilustrate the concept.

    'Format: [-][Days{d,Space}][Horas][{h,':'}[Minutos]]
    <DebuggerStepThrough()> _
    Public Shared Function Parse(ByVal Dato As Object) As Int32
        Dim s As String = TryCast(Dato, String) 'Permite DbNull    
        If s Is Nothing Then Return 0
        s = s.Trim
        Dim v, ac, state As Integer, LastCharDigit, Negativo As Boolean
        For n As Integer = 0 To s.Length - 1
           Dim Digit As Integer = CharUnicodeInfo.GetDigitValue(s, n) '-1 si no es dígito
           If Digit >= 0 Then v = v * 10 + Digit : LastCharDigit = True : Continue For
           Select Case Char.ToLower(s(n))
                Case "d"c
                    If state = 0 Then state = 1 : ac = v * 1440 : v = 0 Else Throw New FormatException("Invalid Format - d")
                Case ":"c, "h"c
                    If state < 2 Then state = 2 : ac += v * 60 : v = 0 Else Throw New FormatException("Invalid Format - :")
                Case " "c : If LastCharDigit = False Then Continue For
                            If state > 0 Then Throw New FormatException("Espacio inválido")
                            state = 1 : ac = v * 1440 : v = 0 'Asumo "d"c
                Case "-"c : If n = 0 Then Negativo = True Else Throw New FormatException("Invalid Format - Caracter invalido")
                Case Else : Throw New FormatException("Invalid Format - Caracter invalido")
           End Select
           LastCharDigit = False
        Next
        If state < 2 Then v *= 60 'Por defecto Horas
        ac += v
        Return If(Negativo, -ac, ac)
    End Function
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:

Select allOpen in new window

 

by: jamesrhPosted on 2009-10-23 at 20:26:07ID: 25650602

The idea of course would be to use the regular expression and string replacement inside a function or property.

 

by: InternalStaticPosted on 2009-10-23 at 22:21:27ID: 25650914

Yeah... there are a few things wrong with the code posted above:

  1. It's in Spanish 
  2. It's in VB 
  3. It's in VB 
  4. I'm not sure what "concept" is really even being illustrated. 
  5. It's in VB. 

Barf.

Author: please be more specific as to your request. What is the purpose of this validation? Do you have any resolution preferenes (eg do you prefer not to use RegEx?)? Let us know.

 

by: Tony_kPosted on 2009-10-24 at 05:55:09ID: 25651944

I want to write a property in C# to test the format of a string called Vcode that is in a constructor, so the user is assigning a string input called Vcode I want to test if this string has a format like the following:

LetterDigitLetterDigitLetterDigit (eg:P6T4K9) and sometimes the user assigns a string with a space between the Letter and the Digit, like LetterDigitLetter DigitLetterdigit (eg: P7Y 8L4) I want to eliminate any space between the letters and the digits in the string and concatenate the whole thing (maybe we can use the Trim Function to eliminate the space in between the characters and the digits. and finally the user might assign a string to the contructor that includes a dash between the letter and the digit, Like LetterDigit-LetterDigitLetterDigit (eg: J8-Y6K5) so I want to eliminate the dashes between the Letter and the digit and concatenate.(maybe also we can use the Trim function). All those scenarios mentioned above are valid input of string and anything else is not valid.

Can anyone help me to do this function in C#?

 

by: Tony_kPosted on 2009-10-24 at 05:57:59ID: 25651951

jamesrh: it can be a function to test the user input  VCODE too.

 

by: Tony_kPosted on 2009-10-24 at 06:38:44ID: 25652140

In other words the string Vcode should have this format: LetterDigitLetterDigitLetterDigit if a dash or a whiteSpace are in between they should be eliminated and then concatenated to have this format LetterDigitLetterDigitLetterDigit. anything else is not Valid.

 

by: Tony_kPosted on 2009-10-24 at 07:04:21ID: 25652241

Please find below what the function should achieve for user string input Vcode:

1. First  It will check if the string input contains whiteSpaces or Dashes
2. if so it should Eliminate the Whitespaces and the Dashes then Concatenate
3. Then it will Check the Length of the string is it is equal to 6 if so it will check the string format if it follows this format LetterDigitLetterDigitLetterDigit  

if all those 3 are true then return errorCode = 0  which is success or Valid

Else

If any of these is wrong  return errorCode = 3. Which is not Valid

 

by: jamesrhPosted on 2009-10-24 at 08:26:55ID: 25652616

Sorry to be a little dense with this, but I want to make sure I am really giving you what you are looking for.  You would like to be use this something like?:

Class1 myClass = new Class1("P6T4K9");
myClass.Vcode = "P7Y 8L4";
string currentVcode = myClass.Vcode;  // currentVcode now = "P7Y8L4"

If this is what you are trying to do, then you need something like the following code:

using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;  
 
namespace Test
{
    class Class1
    {
        private string _Vcode;
 
        public string Vcode
        {
            get { return Vcode; }
            set
            {
                if (!Regex.IsMatch(value, @"[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d"))
                    //we throw an exception because setting a property can't return a value
                    //also when called by the constructor you can't send back a return code
                    throw new Exception("Invalid Vcode format");
 
                _Vcode = value.Replace(" ", "").Replace("-", "");
            }
        }
 
        //for a lot of reasons it is a good idea to have a default constructor
        public Class1()
        { 
            //do any initialization that doesn't depend on parameters
        }
 
        public Class1(string vCode)
        {
            //call it this way to invoke the validation code above.
            this.Vcode = vCode;   
        }
    }
}
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:

Select allOpen in new window

 

by: jamesrhPosted on 2009-10-24 at 08:33:09ID: 25652637

The code I gave you has a couple of caveats.  1) P6T-4K9 and P6T 4K9 are valid. P6T--4K9, P6T -4K9, P6T  4K9, etc are not.  (I would be a small adjustment to change this if necessary)  2)  You could do everything will Regex and captures, however, I wanted to make the code a simple and straightforward as was practical.  If you want to make the change mentioned in item 1, we would then get rid of the replace and use regex and captures.

 

by: Tony_kPosted on 2009-10-24 at 09:02:22ID: 25652760

Jamesrh:
Thank you for code, I think it is answering my question, but I want to double check on this:

Does this expression:   !Regex.IsMatch(value, @"[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d"))
 take care of having this sequence of string format Valid:

LetterDigitLetter-DigitLetterDigit (eg:K2H-7A1) should eliminate the - and concatenate
or
LetterDigitLetter DigitLetterDigit (eg: K2H 7A1) should eliminate the whiteSpace and concatenate to be like this LetterdigitLetterDigitLetterDigit (eg:K2H7A1)

and does this expression take care of the length of the string just to be = 6 after concatenation otherwise not valid.

I want just to double check on the above to give you the 500 full points? :))




 

by: Tony_kPosted on 2009-10-24 at 09:06:18ID: 25652778

Jamesrh: Can you please transform everything to a function instead of a property?

 

by: jamesrhPosted on 2009-10-24 at 09:42:32ID: 25652970

The below is the code in function format.  Notice the regular expression is slightly different as my first example did not check for additional characters before and after.  So the regex tests for the following 3 formats for vCode coming in:  M1M1M1, M1M-1M1, M1M 1M1.  Anything else including additional characters before or after the pattern results in return 3.  The replace statement removes the space or dash if there is one.

You would call the code like so:
string testVcode = "K2H-7A1";
if(EvaluateVcode(ref testVcode) != 3)
   //do some stuff
  //at this point testVcode = K2H7A1

public int EvaluateVcode(ref string vCode)
{
  if (!Regex.IsMatch(value, @"^[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d$"))
     return 3;
 
  vCode = value.Replace(" ", "").Replace("-", "");  
  return 0;   
   
}

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:

Select allOpen in new window

 

by: Tony_kPosted on 2009-10-24 at 12:09:50ID: 25653787

james:
When I build the project it is complaining about the value, im getting "the name 'value' does not exist in the current context".
I am using this reference below:
using System.Text.RegularExpressions;  


any solution about it?

 

by: jamesrhPosted on 2009-10-24 at 12:32:05ID: 25653868

Sorry. When I changed the code I should have replaced value with vCode like so:

public int EvaluateVcode(ref string vCode)
{
  if (!Regex.IsMatch(vCode, @"^[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d$"))
     return 3;
 
  vCode = vCode.Replace(" ", "").Replace("-", "");  
  return 0;   
   
}
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:

Select allOpen in new window

 

by: jamesrhPosted on 2009-10-24 at 12:33:02ID: 25653874

value was only vaild in the property scenario.

 

by: Tony_kPosted on 2009-10-24 at 13:46:24ID: 25654237

yep it works! thanks a million!!!

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...