C# Formatting a string with string.Format("00-00-00") - c#

I am attempting convert this string "123456" to "12-34-56".
I try to use this code but it doesn't seem to work correctly
string.Format("00-00-00", "123456");
Can anyone help me find a suitable pattern? Thanks for any help

Your format string is not correct, composite formatted string should be enclosed within curly braces and can have three parameters as follows,
{ index[,alignment][:formatString] }
While alignment and formatString are optional, index is mandatory.
In your case, it is a single string "123456" with index 0 which is to be formatted in the following pattern "12-34-56".
So, we use the index and format string to achieve the desired output.
To represent a digit 0-9 (optional) in the format string, we use the placeholder '#'.
'#' holds 0, if there exists no digit corresponding to the position in the object, else it replaces the 0 with the digit in place.
The following format string would be suitable for your need,
##-##-## -> three numbers with 2 digits each separated by a hyphen.
Now, putting that in place using the composite format syntax,
"{0:##-##-##}"
Usage:
String input:
var s = "123456";
Console.WriteLine("{0:##-##-##}", Convert.ToInt32(s));
Integer input:
var n = 123456;
Console.WriteLine("{0:##-##-##}", n);

Use below
string.Format("{0:##-##-##}", 123456);
If number is represented as string the convert to int
string.Format("{0:##-##-##}", Convert.ToInt32("123456"));
The above will print the output as
12-34-56

Related

Need to extract data from a variable seperated by back slashes

I have a variable that I need to extract data from separated by a back slash.
My variable data would be
A\123\FRONT\BACK\49585856
I need to extract the second piece based on the back slashes
Thanks in advance!
I haven't tried anything yet since I am having trouble finding documention
as #rufus said
string x = #"A\123\FRONT\BACK\49585856";
string[] b = x.Split('\\');
Console.WriteLine(b[2]);
The method you need is Split
Split is used to break a delimited string into substrings. You can use either a character array or a string array to specify zero or more delimiting characters or strings. If no delimiting characters are specified, the string is split at white-space characters.
using System;
public class SplitExample
{
public static void Main(string[] args)
{
const char separator = '\\';
string data = #"A\123\FRONT\BACK\49585856";
string[] myVariables = data.Split(separator);
Console.WriteLine(myVariables[1]); // myVariables[1] = 123
}
}
Altought if you always need only the second element:
The Split method is not always the best way to break a delimited string into substrings. If you don't want to extract all of the substrings of a delimited string, or if you want to parse a string based on a pattern instead of a set of delimiter characters, consider using regular expressions, or combine one of the search methods that returns the index of a character with the Substring method. For more information, see Extract substrings from a string.

Use regular expression in C# to select a specific occurrence from a string by limiting input

Using C#, i am stuck while trying to extract a specific string while limiting the string to be matched. Here is my input string:
NPS_CNTY01_10112018_Adult_Submittal.txt
I would like to extract 01 after CNTY and ingnore anything after 01.
So far i have the regex to be:
(?!NPS_CNTY)\d{2}
But the above regex gets many other digit matches from the input string. One approach i was thinking was to limit the input to 9 characters to eventually get 01. But somehow not able to achieve that. Any help is appreciated.
I would like to add that the only variable data in this input string is:
NPS_CNTY[two digit county code excluding this bracket]_[date in MMDDYYYY format excluding the brackets]_Adult_Submittal.txt.
Also please limit solutions to regex's.
The (?!NPS_CNTY)\d{2} pattern matches a location that is not immediately followed with NPS_CNTY and then matches 2 digits. The lookahead always returns true since two digits cannot start a NPS_CNTY char sequence, it is redundant.
You may use a positive lookbehind like this to get 01:
var m = Regex.Match(s, #"(?<=NPS_CNTY)\d+");
var result = "";
if (m.Success)
{
result = m.Value;
}
See the .NET regex demo
Here, (?<=NPS_CNTY), a positive lookbehind, matches a location that is immediately preceded with NPS_CNTY and then \d+ matches 1 or more digits.
An equivalent solution using capturing mechanism is
var m = Regex.Match(s, #"NPS_CNTY(\d+)");
var result = "";
if (m.Success)
{
result = m.Groups[1].Value;
}
If the string always start with NPS_CNTY and you have to extract 2 digits then you don't need a regular expression. Just use Substring() method:
string text = #"NPS_CNTY01_01141980_Adult_Submittal.txt";
string digits = text.Substring(8, 2);
EDIT:
In case you need to match N digits after NPS_CNTY you can use the following code:
string text = #"NPS_CNTY012_01141980_Adult_Submittal.txt";
string digits = text.Replace("NPS_CNTY", string.Empty)
.Split("_", StringSplitOptions.RemoveEmptyEntries)
.FirstOrDefault();

How to find out if a string contains digits followed by alphabet characters?

How can I find out whether a given string contains at least one number followed by alphabets using Regex in c#?
For example :
var strInput="Test123Test";
The function should return a bool value.
result = Regex.IsMatch(subjectString, #"\d\p{L}");
will return True for your sample string. Currently, this regex also considers non-ASCII digits and letters as valid matches, if you don't want that, use #"[0-9][A-Za-z])" instead.
If you want to match 123 only then:-
Match m = Regex.Match("Test123Test", #"(\p{L}+)(\d+)") ;
string result = m.Groups[2].Value
If you want to get the bool value then do this:-
Console.WriteLine(!String.IsNullOrEmtpty(result))) ;
or simple use:-
Regex.IsMatch("Test123Test", #"\p{L}+\d+") ;
Try this:
if(Regex.IsMatch(strInput, #"[0-9][A-Za-z]"))
...

How to extract a number from brackets (an ending part of a string)?

My question concerns extracting an integer number from a string (in C#). There is a string which can have an integer positive number in round brackets in the end (without leading zeros), e.g. "This is a string (125)". I would like to write a code validating whether it has such a form, and if so, extracting the number and the rest from it. For example, if the string were "This is a string (125)", the results should be "This is a string" (type: string), and 125 (integer). If the string were "Another example (7)", the results should be "Another example", and 7. Would regex be useful, or should I rather write a parsing function?
If the input value always has same structure (like /type/bracket/value/bracket) then you can do it via:
1) RegEx
2) String.Split()
3) String.IndexOf()
Use the regular expression \((\d})\)$ that will much the number to the end of the string as a group.
string testString = "This is a string (125)asbcd";
string[] stringPart = testString.Split('(', ')');
Here stringPart[0] is the string part, and stringPart[1] is the numeric part.
You can try this
string firstPart = Regex.Match(inputString, #"\(([^)]*)\)").Groups[0].Value;
int number;
Int32.TryParse(Regex.Match(inputString, #"\(([^)]*)\)").Groups[1].Value, out number);
EDIT:
Obviously you can optimise this and not do the Match twice but this shows how to use it.

Adding whitespaces to a string in C#

I'm getting a string as a parameter.
Every string should take 30 characters and after I check its length I want to add whitespaces to the end of the string.
E.g. if the passed string is 25 characters long, I want to add 5 more whitespaces.
The question is, how do I add whitespaces to a string?
You can use String.PadRight for this.
Returns a new string that left-aligns the characters in this string by padding them with spaces on the right, for a specified total length.
For example:
string paddedParam = param.PadRight(30);
You can use String.PadRight method for this;
Returns a new string of a specified length in which the end of the
current string is padded with spaces or with a specified Unicode
character.
string s = "cat".PadRight(10);
string s2 = "poodle".PadRight(10);
Console.Write(s);
Console.WriteLine("feline");
Console.Write(s2);
Console.WriteLine("canine");
Output will be;
cat feline
poodle canine
Here is a DEMO.
PadRight adds spaces to the right of strings. It makes text easier to
read or store in databases. Padding a string adds whitespace or other
characters to the beginning or end. PadRight supports any character
for padding, not just a space.
Use String.PadRight which will space out a string so it is as long as the int provided.
var str = "hello world";
var padded = str.PadRight(30);
// padded = "hello world "
you can use Padding in C#
eg
string s = "Example";
s=s.PadRight(30);
I hope It will resolve your problem.

Categories

Resources