How to remove DateTime substring from string - c#

I have a bunch of strings, some of which have one of the following formats:
"TestA (3/12/10)"
"TestB (10/12/10)"
The DateTime portion of the strings will always be in mm/dd/yy format.
What I want to do is remove the whole DateTime part including the parenthesis. If it was always the same length I would just get the index of / and subtract that by the number of characters up to and including the (. But since the mm portion of the string could be one or two characters, I can't do that.
So is there a way to do a .Contains or something to see if the string contains the specified DateTime format?

You could use a Regular Expression to strip out the possible date portions if you can be sure they would consistently be in a certain format using the Regex.Replace() method :
var updatedDate = Regex.Replace(yourDate,#"\(\d{1,2}\/\d{1,2}\/\d{1,2}\)","");
You can see a working example of it here, which yields the following output :
TestA (3/12/10) > TestA
TestB (10/12/10) > TestB
TestD (4/5/15) > TestC
TestD (4/6/15) > TestD

You could always use a regular expression to replace the strings
Here is an example
var regEx = new Regex(#"\(\d{1,2}\/\d{1,2}\/\d{1,2}\)");
var text = regEx.Replace("TestA (3/12/10)", "");

Use a RegEx for this. I recommend:
\(\d{1,2}\/\d{1,2}\/\d{1,2}\)
See RegExr for it working.

Regex could be used for this, something such as:
string replace = "TestA (3/12/10) as well as TestB (10/12/10)";
string replaced = Regex.Replace(replace, "\\(\\d+/\\d+/\\d+\\)", "");

If I'm understanding this correctly you want to just acquire the test name of each string. Copy this code to a button click event.
string Old_Date = "Test SomeName(3/12/10)";
string No_Date = "";
int Date_Pos = 0;
Date_Pos = Old_Date.IndexOf("(");
No_Date = Old_Date.Remove(Date_Pos).Trim();
MessageBox.Show(No_Date, "Your Updated String", MessageBoxButton.OK);
To sum it up in one line of code
No_Date = Old_Date.Remove(Old_Date.IndexOf("(")).Trim();

Related

How can i create a dynamic string format in C#

I have as input the string format CST-000000 and an integer with value 1
Upon using
string result = string.Format("CST-000000", 1);
the expected result should be CST-000001 instead of CST-000000
How could i create this string format dynamically?
For example
- CST-000 should produce CST-001
- HELLO000 should produce HELLO001
- CUSTOMER0000 should produce CUSTOMER0001
Assuming that:
You receive your format string from somewhere and you can't control what it looks like
Your format string ends with 1 or more zeros
If the format string is e.g. CST-00000 and your value is 123, you want the result to be CST-00123
You can do something like this:
Inspect your format string, and separate out the stuff at the beginning from the zeros at the end. It's easy to do this with Regex, e.g.:
string format = "CST-000000";
// "Zero or more of anything, followed by one or more zeros at the end of the string"
var match = Regex.Match(format, "(.*?)(0+)$");
if (!match.Success)
{
throw new ArgumentException("Format must end with one or more zeros");
}
string prefix = match.Groups[1].Value; // E.g. CST-
string zeros = match.Groups[2].Value; // E.g. 000000
Once you have these, note the "Zero placeholder" in this list of custom numeric format strings -- you can write e.g. 123.ToString("0000") and the output will be 0123. This lets you finish off with:
int value = 123;
string result = prefix + value.ToString(zeros);
See it on dotnetfiddle
String.Format requires a placeholder {n} with a zero-based argument number. You can also add it a format {n:format}.
string result = String.Format("CST-{0:000000}", 1);
You can also use String interpolation
string result = $"CST-{1:000000}"
The difference is that instead of a placeholder you specify the value directly (or as an expression). Instead of the Custom numeric format string, you can also use the Standard numeric format string d6: $"CST-{1:d6}"
If you want to change the format template dynamically, String.Format will work better, as you can specify the format and the value as separate arguments.
(Example assumes an enum FormatKind and C# >= 8.0)
int value = 1;
string format = formatKind switch {
FormatKind.CstSmall => "CST-{0:d3}",
FormatKind.CstLarge => "CST-{0:d6}",
FormatKind.Hello => "HELLO{0:d3}",
FormatEnum.Customer => "CUSTOMER{0:d4}"
};
string result = String.Format(format, value);
Also note that the value to be formatted must be of a numeric type. Strings cannot be formatted.
See also: Composite formatting
It seems .toString("CST-000"), .toString("HELLO000") and so on, does the trick.
ToString and String.Format can do much more than use predefined formats.
For example :
string result = string.Format("CST-{0:000000}", 1);
string result = 1.ToString("CST-000000");
Should both do what you want.
(Of course you could replace "1" by any variable, even a decimal one).

C# - How to format datetime to remove trailing zeros

I'm setting up an orchestration class that handles multiple actions as one big transaction. For each of these transactions I give them the same time-stamp instantiated at the beginning of the orchestration.
I user the following line:
var transactionTimestamp = DateTime.UtcNow.ToString("o");
I have a constraint in the system that dictates that the time stamp cannot have any trailing zeros.
For example:
2013-06-26T19:51:38.0083980Z //bad
2013-06-26T19:51:38.008398Z //good
2013-06-26T19:51:38.0083988Z //good
The built-in DateTime format "o" is comparable to the custom format of: "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK". If you just use that format, but replace the lower-case f's with upper case ones, there will be no trailing zeros.
ie
DateTime.UtcNow.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'FFFFFFFK");
Custom date and time format strings
You can achieve this fairly easily using Regex. Here's one way.
string result = Regex.Replace("2013-06-26T19:51:38.0083980Z", "0+Z$", "Z");
// result == "2013-06-26T19:51:38.008398Z"
string result2 = Regex.Replace("2013-06-26T19:51:38.0083988Z", "0+Z$", "Z")
// result2 == "2013-06-26T19:51:38.0083988Z"
I would write my own help method like;
public string GetDtString(DateTime dt)
{
RegEx rgx = new RegEx("[1-9]0+Z\b");
return rgx.Replace(dt.ToString("o"), System.String.Empty);
}
It basically just returns the dt string with all 0's which occur after a digit 1-9 and before Z\b (Z followed by a word boundary) with an empty string.

Regular expression for parsing CSV

I'm trying to parse a CSV file in C#. Split on commas (,). I got it to work with this:
[\t,](?=(?:[^\"]|\"[^\"]*\")*$)
Splitting this string:
2012-01-06,"Some text with, comma",,"300,00","143,52"
Gives me:
2012-01-06
"Some text with, comma"
"300,00"
"143,52"
But I can't figure out how to lose the "" from the output so I get this instead:
2012-01-06
Some text with, comma
300,00
143,52
Any suggestions?
If you are trying to parse a CSV and using .NET, don't use regular expressions. Use a component that was created for this purpose. See the question CSV File Imports in .Net.
I know the CSV specification looks simple enough, but trust me, you are in for heartache and destruction if you continue down this path.
Why are you using regular expressions for this? Ensuring the file is well-formed?
You can use String.Replace()
String s = "Some text with, comma";
s = s.Replace("\"", "");
// After matched
String line = 2012-01-06,"Some text with, comma",,"300,00","143,52";
String []fields = line.Split(',');
for (int i = 0; i < fields.Length; i++)
{
// Call a function to remove quotes
fields[i] = removeQuotes(fields[i]);
}
String removeQuotes(String s)
{
return s.Replace("\"", "");
}
So, something like this. Again, I wouldn't use RegEx for this purpose, but YMMV.
var sp = Regex.Split(a, "[\t,](?=(?:[^\"]|\"[^\"]*\")*$)")
.Select(s => Regex.Replace(s.Replace("\"\"","\""),"^\"|\"$","")).ToArray();
So, the idea here is that first of all, you want to replace double double quotes with a single double quote. And then that string is fed to the second regex which simply removes double quotes at the beginning and end of the string.
The reason for the first replace is because of strings like this:
var a = "1999,Chevy,\"Venture \"\"Extended Edition, Very Large\"\" Dude\",\"\",\"5000.00\"";
So, this would give you a string like this: ""Extended Edition"", and the double quotes need to be changed to single quotes.

parsing a string into int/long using custom format strings

In C#.Net, here's a simple example of how to format numbers into strings using custom format strings:
(example taken from: http://www.csharp-examples.net/string-format-int/)
String.Format("{0:+### ### ### ###}", 447900123456); // "+447 900 123 456"
String.Format("{0:##-####-####}", 8958712551); // "89-5871-2551"
Is there a way to convert this formatted string back into a long/integer ? Is there someway to do this :
long PhoneNumber = Int32.Parse("89-5871-2551", "{0:##-####-####}");
I saw that DateTime has a method ParseExact which can do this work well. But I did not see any such thing for int/long/decimal/double.
You can regex out all of the non numeric numbers, and what you're left with is a string of numbers that you can parse.
var myPhoneNumber = "89-5871-2551";
var strippedPhoneNumber = Regex.Replace(myPhoneNumber, #"[^\d]", "");
int intRepresentation;
if (Int32.TryParse(strippedPhoneNumber, out intRepresentation))
{
// It was assigned, intRepresentation = 8958712551
// now you can use intRepresentation.
} else {
// It was not assigned, intRepresentation is still null.
}
Well, you can always do
long PhoneNumber = Int32.Parse("89-5871-2551".
Replace(new char[]{'-','+',whatever..}).Trim());
By the way, considering that you're parsing a string received from some IO, I would suggest to use more secure (in terms of conversion) Int32.TryParse method.
The way like you described doesn't actually exist.
Just Regex out all of the non-numeric characters, then parse that string.

Remove last characters from a string in C#. An elegant way?

I have a numeric string like this 2223,00. I would like to transform it to 2223. This is: without the information after the ",". Assume that there will be only two decimals after the ",".
I did:
str = str.Remove(str.Length - 3, 3);
Is there a more elegant solution? Maybe using another function? -I donĀ“t like putting explicit numbers-
You can actually just use the Remove overload that takes one parameter:
str = str.Remove(str.Length - 3);
However, if you're trying to avoid hard coding the length, you can use:
str = str.Remove(str.IndexOf(','));
Perhaps this:
str = str.Split(",").First();
This will return to you a string excluding everything after the comma
str = str.Substring(0, str.IndexOf(','));
Of course, this assumes your string actually has a comma with decimals. The above code will fail if it doesn't. You'd want to do more checks:
commaPos = str.IndexOf(',');
if(commaPos != -1)
str = str.Substring(0, commaPos)
I'm assuming you're working with a string to begin with. Ideally, if you're working with a number to begin with, like a float or double, you could just cast it to an int, then do myInt.ToString() like:
myInt = (int)double.Parse(myString)
This parses the double using the current culture (here in the US, we use . for decimal points). However, this again assumes that your input string is can be parsed.
String.Format("{0:0}", 123.4567); // "123"
If your initial value is a decimal into a string, you will need to convert
String.Format("{0:0}", double.Parse("3.5", CultureInfo.InvariantCulture)) //3.5
In this example, I choose Invariant culture but you could use the one you want.
I prefer using the Formatting function because you never know if the decimal may contain 2 or 3 leading number in the future.
Edit: You can also use Truncate to remove all after the , or .
Console.WriteLine(Decimal.Truncate(Convert.ToDecimal("3,5")));
Use:
public static class StringExtensions
{
/// <summary>
/// Cut End. "12".SubstringFromEnd(1) -> "1"
/// </summary>
public static string SubstringFromEnd(this string value, int startindex)
{
if (string.IsNullOrEmpty(value)) return value;
return value.Substring(0, value.Length - startindex);
}
}
I prefer an extension method here for two reasons:
I can chain it with Substring.
Example: f1.Substring(directorypathLength).SubstringFromEnd(1)
Speed.
You could use LastIndexOf and Substring combined to get all characters to the left of the last index of the comma within the sting.
string var = var.Substring(0, var.LastIndexOf(','));
You can use TrimEnd. It's efficient as well and looks clean.
"Name,".TrimEnd(',');
Try the following. It worked for me:
str = str.Split(',').Last();
Since C# 8.0 it has been possible to do this with a range operator.
string textValue = "2223,00";
textValue = textValue[0..^3];
Console.WriteLine(textValue);
This would output the string 2223.
The 0 says that it should start from the zeroth position in the string
The .. says that it should take the range between the operands on either side
The ^ says that it should take the operand relative to the end of the sequence
The 3 says that it should end from the third position in the string
Use lastIndexOf. Like:
string var = var.lastIndexOf(',');

Categories