Reputation: 1237
I need to build a method that can return me the string like this
00:00:00:00
hh:mm:ss:fr
If I pass 10 seconds to the method it should give the output : 00:00:10:00
, So if minutes/hours/frames are null, it should enter 00.as in this example.
public static string ToTimeCode(string hours, string minutes, string seconds, string frames)
{
string timeCodeString
// should I do some IF loops here to check for nulls and build the timecode string
return timeCodeString;
}
Is this possible with regular expressions.
Upvotes: 1
Views: 1050
Reputation: 15175
I think with a little bit of googling you could have found the answer yourself.
The unanswered question is, when for example hour is 0 do you receive 00
in the string? Or is it null? Assuming everything is as you expect you can just interpolate the string:
return $"{hour ?? "00"}:{minute ?? "00"}:{second ?? "00"}:{frames ?? "00"}";
A simple (and inefficient) C# 5.0 version as requested in the comments could be:
return
(hour == null ? "00" : hour)
+ ":"
+ (minute == null ? "00" : minute)
+ ":"
+ (second == null ? "00" : second)
+ ":"
+ (frames == null ? "00" : frames);
Upvotes: 2
Reputation: 2879
using System;
namespace ConsoleApp26
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(ToTimeCode(null,null,"10",null));
Console.WriteLine(ToTimeCode("1", "2", "3", "4"));
Console.WriteLine(ToTimeCode2(null, null, "10", null));
Console.WriteLine(ToTimeCode2("1", "2", "3", "4"));
Console.ReadLine();
}
public static string ToTimeCode(string hours, string minutes, string seconds, string frames)
{
int.TryParse(hours, out int hoursInt);
int.TryParse(minutes, out int minutesInt);
int.TryParse(seconds, out int secondsInt);
int.TryParse(frames, out int framesInt);
var timespan = new TimeSpan(hoursInt, minutesInt, secondsInt, framesInt);
return timespan.ToString("g");
}
public static string ToTimeCode2(string hours, string minutes, string seconds, string frames)
{
int.TryParse(hours, out int hoursInt);
int.TryParse(minutes, out int minutesInt);
int.TryParse(seconds, out int secondsInt);
int.TryParse(frames, out int framesInt);
var timespan = new TimeSpan(hoursInt, minutesInt, secondsInt, framesInt);
return timespan.ToString(@"dd\.hh\:mm\:ss");
}
}
}
Output:
0:10:00
1:2:03:04
00.00:10:00
01.02:03:04
If u give wrong format or null to string parametrs, it will 0 at the output
Upvotes: 0