Validating and storing comma separated values - c#

I have a split string,
string s = Console.ReadLine();
string[] values = s.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
s should receive input like this:
string literal, numeric value, numeric value, numeric value OR string literal
I realize that all this input gets read as a string, but I'm trying to validate the numbers in the string (checking for >0), as well as assign each value in the string to a variable. What would be the best way to go about this?

You're looking for a specific pattern. I'd suggest to use a regex, and then get the number groups - and do the > 0 validation check.

string s = Console.ReadLine();
string[] values = s.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
string stringValue0 = values[0];
int numericValue1 = int.Parse(value[1]); // Assuming the value is an valid interger.
int numericValue2 = int.Parse(value[2]); // Assuming the value is an valid interger.
int numericvalue3;
string stringValue3;
if (!int.TryParse(values[3], out numericValue3) // Trying to convert the text to an interger. If it fails, assign it to the stringValue3.
stringValue3 = values[3];
You can always use int.TryParse to validate if a text contains a number.

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).

How to make string of specified length from another string c#

For example I have strings like:
"5", "8", "14", "260"
and I want to get result like:
"ST00000005", "ST00000008", "ST00000014", "ST00000260"
result string length is 10 chars. How can I do it?
I would store it as int not as string. Then you can use ToString with the appropriate format specifier D8. That has f.e. the advantage that you can increase the number:
int number = 5;
string result = String.Format("ST{0}", number.ToString("D8"));
or without ToString but only String.Format:
string result = String.Format("ST{0:D8}", number);
Read: Standard Numeric Format Strings especially Decimal ("D") Format Specifier
If you need to convert a string to int use int.Parse or int.TryParse.
For the sake of completeness, if you have to use strings use String.PadLeft(8, '0'):
string numStr = "5";
String result = String.Format("ST{0}", numStr.PadLeft(8, '0'));
int number = 5; // put the number here
string result = $"ST{number:0000000#}";
// Or:
string result = $"ST{number:D8}";
This does exactly what you want.
EDIT: Keep in mind that this is only possible in C#6
You can do this like
string s = "215";
s = s.PadLeft(8, '0').PadLeft(9,'T').PadLeft(10,'S');
Use string.Format() together with a custom format string.

How to use Substring , to return an integer of all the values after the first char

I have an string AssetNumber that have the following format C100200.
so i need to do the folloiwng:-
Get all the characters after the first (e.g. 100200 using above example)
Convert the substring to integer
Return the integer + 1
but I do not know how to use the sub-string to get all the characters after the first char, and how to convert string into int? Any help on this will be appreciated.
var result = Int32.Parse("C100200".Substring(1)) + 1;
If you would like to have default value, if you can't parse current string:
int result;
if (!Int32.TryParse("sdfsdf".Substring(1), out result)) {
result = 42;
}
result+=1;

how to assign a char value to string variable in c#

i have a string strText with certain value on it,i need to assign '\0' or charactor at the specified position of strText.
ie strText[5]='\0'.how is it possible in c#.
You can use the Insert method to specify the index. You need to give it a string though, so if you can replace '\0' with "\0" or else just call .ToString()
strText = strText.Insert(5, yourChar.ToString());
Strings are immutable, so you will need to convert it to a character array, set the character at the specified position, and then convert back to string:
char[] characters = "ABCDEFG".ToCharArray ();
characters[5] = '\0';
string foo = new String (characters);

using numbers in a string

Can I use numbers while using String data type?
Sure you can, and if you want to use them as numbers you can parse the string. E.g. for an integer:
string numberAsString = "42";
int numberFromString;
if (int.TryParse(numberAsString, out numberFromString))
{
// number successfully parsed from string
}
TryParse will return a bool telling if the parsing were successful. You can also parse directly if you know the string contains a number - using Parse. This will throw if the string can't be parsed.
int number = int.Parse("42");
You can have numbers in a string.
string s = "123";
..but + will concatenate strings:
string s = "123";
string other = "4";
Debug.Assert(s + other != "127");
Debug.Assert(s + other == "1234");
Numbers can be easily represented in a string:
string str = "10";
string str = "01";
string str = 9.ToString();
However, these are strings and cannot be used as numbers directly, you can't use arithmetic operations on them and expect it to work:
"10" + "10"; // Becomes "1010"
"10" / "10"; // Will not compile
You can easily store numbers as a string:
string foo = "123";
but that only helps you if you actually want numbers in a string. For arithmetic purposes, use a number. If you need to display that later, us a format string.
String number1 = "123456";
keep in mind. using that number for arithmatic purpose, you have to convert that string into proper type like
int number1Converted = Int32.Parse(number1);
int.TryParse(number1 , out number1Converted );
for double
double doubleResult = 0.0;
double.TryParse("123.00", out doubleResult);

Categories