I'm trying to format a string of 6 digits with the following format:
1234/56.
I'm using the following:
string.Format("123456", "{0000/00}");
Result 123456
Try something like
var number = int.Parse("123456");
var formattedNumber = number.ToString("####/##", CultureInfo.InvariantCulture);
Edit to include zero fill (if required):
var number = int.Parse("123456");
var formattedNumber = number.ToString("####/##", CultureInfo.InvariantCulture).PadLeft(7,'0');
You will still have issues with any number below 10 (i.e "000009") showing up as 0000/9. In which you are probably better off with a substring modification like below.
var text = "123456";
var formattedNumber = text.Substring(0, 4) + "/" + text.Substring(4, 2);
Please try the below code.
string.Format("{0:####/##}",123456)
I tested the code and is working.
For reference on string formatting please visit:
https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings
If you are using numbers I would use #rob-s 's example above. If you are dealing with actual strings then you can use the following code sample.
var value = "123456";
var index = value.Length - 2;
var formattedValue = $"{value.Substring(0, index)}/{value.Substring(index)}";
Console.WriteLine(formattedValue);
Your output will look like what you have described in your question.
1234/56
Related
The below code works fine. But, I want to obtain this via Regex.
private decimal GetQuarter(string quarter)
{
var unformattedQuarter = "20" + quarter[2] + quarter[3] + "." + quarter[6];
return Convert.ToDecimal(unformattedQuarter);
}
Input
FY18 Q4
FY19 Q1
FY19 Q2
Output
2018.4
2019.1
2019.2
You can use the pattern
FY(\d{2}) Q(\d)
And replace matches with
20$1.$2
Example
var input = #"FY18 Q4\r\nFY19 Q1\r\nFY19 Q2";
var pattern = #"FY(\d{2}) Q(\d)";
var replacement = "20$1.$2";
Console.WriteLine(Regex.Replace(input, pattern, replacement));
Output
2018.4
2019.1
2019.2
Full Demo Here
Explanation
Note : Adding 20 seems a little problematic, and should be used with caution
Using the following code, you can extract the first and second occurrences of the numbers from the string into a list and then concatenate them:
string n = "FY18 Q1";
Regex digits = new Regex(#"[\d]+");
var list = digits.Matches(n);
var finalValue = "20" + list [0] + "." + list [1];
Pretty sure we all do string.format and define some string in a specifed format.
I have a string which is always formatted in a way like this:
const string myString = string.Format("pt:{0}-first:{1}", inputString);
To get {0}, I can always check for pt:{ and read till }.
But what is the best/recommended way to extract {0} & {1} from the above variable myString ?
A Regex version of answer, but again, assuming your input doesnt contain '-'
var example = = "pt:hello-first:23";
var str = "pt:(?<First>[^-]+)-first:(?<Second>[^%]+)";
var match = new Regex(str).Match(example);
var first = match.Groups["First"].Value;
var second = match.Groups["Second"].Value;
It might be a good idea that you define what your variable can/cannot contain.
Not sure if this is the best way to do it, but it's the most obvious:
string example = "pt:123-first:456";
var split = example.Split('-');
var pt = split[0].Substring(split[0].IndexOf(':') + 1);
var first = split[1].Substring(split[1].IndexOf(':') + 1);
As Shawn said, if you can guarantee that the variables wont contain either : or - this will be adequate.
I am using code for splitting :
columnVal = val.Contains(":") ? val.Split(':')[1] : val;
Example #2 Approval Level: Formulator I am getting result Formulator
As per expected ...But
Now having issue when date and time is there
Example #2 Approval Date: 11/18/2015 3:53:22 PM
Result 11/18/2015 3
I am looking for whole string 11/18/2015 3:53:22 PM
What to do in this ? Please help me
You need this overload of string.Split, where you can specify the maximum number of substrings to return:
columnVal = val.Contains(":") ? val.Split(new [] {':'}, 2)[1] : val;
So it will stop splitting after the first :.
If you only want the string split once, rather than at every possible symbol match, use string.SubString and string.IndexOf.
var index = val.IndexOf(':') + 1;
columnVal = (index < val.Length && index >= 0)
? val.Substring(index)
: val;
You need to find the first occurrence of : and take the rest of the string using string.Substring after that in order to get your desired output.
columnVal = val.Contains(":") ? val.Substring(val.IndexOf(':') + 1).Trim() : val;
string parseTarget = "Example #2 Approval Date: 11/18/2015 3:53:22 PM"
int colonPosition = parseTarget.IndexOf(":");
if (colonPosition == -1)
{
throw new Exception("Missing Delimeter");
}
string Value = parseTarget.Substring(colonPosition + 1, parseTarget.Length - colonPosition - 1);
console.WriteLine(Value);
Rather than using String.Split / String.Contains, I would advise using Regex.Split. It's more flexible in that you can specify a maximum amount of positions and different splitting parameters. On top of that it's shorter and more readable than the other answers provided, imo. See Regex documentation
Code snippet for you:
Regex rgx = new Regex(":");
string[] result = rgx.Split(val, 1);
string date = result[1];
Alternatively, you can replace the last line with the following snippet if there will ALWAYS be a split:
string date = rgx.Split(val, 1)[1];
How to solve this?
What i want to change this :
C:\files\team\business\dev\Source\systems\extension\destination\1.0.1.1\
to new value:
value = "1.0.11";
You could just get the Name of the corresponding DirectoryInfo:
string path = #"C:\files\team\business\dev\Source\systems\extension\destination\1.0.1.1\";
string version = new DirectoryInfo(path).Name;
Alternative method:
var path = #"C:\files\team\business\dev\Source\systems\extension\destination\1.0.1.1\";
var value = Path.GetFileName(path.TrimEnd(new[]{'/','\\'}));
// OUTPUT: 1.0.1.1
This basically removes any last directory delimeters and then treats the last directory as a filename, so it returns the last directory.
Based on #JeppeStigNielsen's comments below, here's a better, platform independent alternative.
var value = Path.GetFileName(Path.GetDirectoryName(path));
This will work if there is a file name present as well.
var value = Path.GetFileName(Path.GetDirectoryName(".../1.0.1.1/somefile.etc"));
// returns 1.0.1.1
Darin's answer is great but as an alternative;
string s = #"C:\files\team\business\dev\Source\systems\extension\destination\1.0.1.1\";
string[] array = s.Split('\\');
Console.WriteLine(array[array.Length - 2]);
Output will be;
1.0.1.1
Here a DEMO.
i have string in textbox:
`New-Value = 12,34 -- Old-Values: 12,31,`
what i'd like to do is to get Old-Value so "12,31,"
How can i get from this textbox this specific information do this? So value is between ":" and ","
Tnx
Regex.Match("New-Value = 12,34 -- Old-Values: 12,31,",#"\:(.+)\,").Groups[1].Value.Trim()
const string oldPointer = "Old-Values: ";
var text = "New-Value = 12,34 -- Old-Values: 12,31,";
var old = text.Substring(text.IndexOf(oldPointer) + oldPointer.Length).TrimEnd(',');
Not very clear if this is a fixed (static) format of your string, but by the way:
A simple solution could be:
string str = "New-Value = 12,34 -- Old-Values: 12,31,";
str.Substring(str.IndexOf(':') + 1);
More complex one should involve Regular expressions, like an answer of L.B or others if any.