Click here to Skip to main content
15,895,656 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hello everyone,

I have a string that has a "/" in the middle of it. Either side of this character there are numbers, but this string can change size at any time, but there is always a "/" in the middle of it.

I need to find the number of characters before the "/" and the number of characters after the "/".

The maximum number of characters before the "/" is 4, and the maximum number of characters after the "/" is 2.

I need to see if the number of characters in the first part of the string is 4, if it isn't, I need to add however many zero's to the start of it to make it 4 characters long.

Then I need to see if the number of characters in the second part of the string is 2, if it isn't, I need to add a zero to the start of that part of the string.

Any help is greatly appreciated,
thanks.
Posted

1 solution

I think a regular expression to extract both parts would do the trick here :

C#
Regex regex = new Regex(@"^(?<LeftPart>[\d]?)/(?<RightPart>[\d]?)$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
Match m = regex.Match(yourString);

if (m.Success)
{
   string left = m.Groups["LeftPart"].Value;
   string right = m.Groups["RightPart"].Value;

   while (left.Length < 4)
      left.Insert(0, "0");

   while (right.Length < 2)
      right.Insert(0, "0");
}
else
{
   // Handle error
}


Hope this helps.
Regards.
 
Share this answer
 
v3
Comments
thomasriley 16-Jan-13 8:23am    
Few tweaks as for one I'm in VB.NET but thanks phil.o that seemed to have worked!
phil.o 16-Jan-13 8:24am    
Sorry, it seems I misread the tag of your question.
If you have problems translating to VB let me know.
Glad to help :)

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