using numbers in a string - c#

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

Related

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.

Get exponential value using regular expression

I have string like this:
strings s = "1.0E-20"
Is there a way to get only -20 from this using regex?
I tried this:
(([1-9]+\.[0-9]*)|([1-9]*\.[0-9]+)|([1-9]+))([eE][-+]?[0-9]+)?
this gets me e-20 in group5 but still not just -20.
Use Regex for dealing with text, use Math(s) for dealing with numbers:
Math.Log10(Convert.ToDouble("1.0E-20")) // returns -20
To make sure your string input is a valid double use TryParse:
double d, result = 0.0;
if (Double.TryParse("1.0E-20", out d))
{
result = Math.Log10(d);
}
else
{
// handle error
}
Also, if you want to get the 1.0 (multiplier) from your input:
var d = Convert.ToDouble("1.0E-20");
var exponent = Math.Log10(d);
var multiplier = d / exponent;
No need for Regex when string methods can do wonders
string str = "1.0E-20";
str = str.Substring(str.IndexOf('E') + 1);
You can do that without Regex like:
string s = "1.0E-20";
string newStr = s.Substring(s.IndexOf('E') + 1);
Later you can parse the string to number like:
int number;
if (!int.TryParse(newStr, out number))
{
//invalid number
}
Console.WriteLine(number);
You can also use string.Split like:
string numberString = s.Split('E')[1]; //gives "-20"
Its better if you add check for string/array length when access string.Substring or accessing element 1 after split.
var x = str.IndexOf("E") != -1 ? str.Substring(str.IndexOf("E") + 1) : "1";
If you want to use regular expressions to achieve this, you should switch up your capture groups.
(([1-9]+\.[0-9]*)|([1-9]*\.[0-9]+)|([1-9]+))([eE])([-+]?[0-9]+)?
Group 6 will contain -20 with your given example with the regular expression above. Note how the parentheses have moved. We might need more information from you though. Do you have any more sample data? What's the end goal here?

Validating and storing comma separated values

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.

How to convert a string with a period character to an int?

How do you convert a string with a period character to an int?
I have to convert strings like "1924.912" to int's, but the int.Parse() and Convert.ToInt32() methods don't work here.
Try this:
var str = "1924.912";
var mass = str.Split('.').Select(x => x).ToArray();
Or this:
var str = "1924.912";
var mass = str.Split('.');
To have all decimal like int use next:
var str = "1924.912";
var mass = str.Replace(".","");
You can use Double.Parse() and then convert result to int.
var result = (int)Double.Parse("1924.912");
Optionally you can specify decimal separator because its local specific.
If you want get 1924912 from "1924.912" you can achieve this by replacing "." by "":
string s = "1924.912";
int result = int.Parse(s.Replace(".", ""));
result.Dump();
Will print 1924912.
Do this
string value = "34690.42724";
Convert.ToInt64(Math.Round(Convert.ToDouble(value)));
double.Parse(textBox1.Text.Replace(".",","))
If you want to convert the string "1924.912" to the integer 1924912 disregarding the period you can use this expression where you simply remove any periods in the string before doing the conversion:
Int32.Parse("1924.912".Replace(".", String.Empty))

How can I parse an integer and the remaining string from my string?

I have strings that look like this:
1. abc
2. def
88. ghi
I'd like to be able to get the numbers from the strings and put it into a variable and then get the remainder of the string and put it into another variable. The number is always at the start of the string and there is a period following the number. Is there an easy way that I can parse the one string into a number and a string?
May not be the best way, but, split by the ". " (thank you Kirk)
everything afterwards is a string, and everything before will be a number.
You can call IndexOf and Substring:
int dot = str.IndexOf(".");
int num = int.Parse(str.Remove(dot).Trim());
string rest = str.Substring(dot).Trim();
var input = "1. abc";
var match = Regex.Match(input, #"(?<Number>\d+)\. (?<Text>.*)");
var number = int.Parse(match.Groups["Number"].Value);
var text = match.Groups["Text"].Value;
This should work:
public void Parse(string input)
{
string[] parts = input.Split('.');
int number = int.Parse(parts[0]); // convert the number to int
string str = parts[1].Trim(); // remove extra whitespace around the remaining string
}
The first line will split the string into an array of strings where the first element will be the number and the second will be the remainder of the string.
Then you can convert the number into an integer with int.Parse.
public Tuple<int, string> SplitItem(string item)
{
var parts = item.Split(new[] { '.' });
return Tuple.Create(int.Parse(parts[0]), parts[1].Trim());
}
var tokens = SplitItem("1. abc");
int number = tokens.Item1; // 1
string str = tokens.Item2; // "abc"

Categories