If I have a version number that has 5 digits such as "1.0.420.50.0", how could I truncate this number (and other version numbers like "1.0.512.500.0") to only 4 digits? "1.0.420.50.0" --> "1.0.420.50"
I would prefer to use an array but any other methods work too!
Thanks for any advice in advance!
I haven't programmed in c# in a while so the syntax may be off. If the versioning can be more than six digits, you won't want a method that relies on removing the last digit. Instead just take the first four version numbers.
String version = "1.0.420.50.0";
String [] versionArray = version.Split(".");
var newVersion = string.Join(".", versionArray.Take(4));
If it's a string, you could do something like
ver = "1.2.3.4.5";
ver = ver.substring(0, ver.lastindexof(".");
this should give you all the way up to the last ".". This is not very robust if your version numbers get longer or shorter, but it would work for a 5 digit version number. This is also the basic idea you want if you have a string.
Get the index of the last period and then get the substring from index 0 to the index of the last period. EX:
string version = "1.0.420.50.0";
int lastPeriodIndex = version.LastIndexOf('.');
string reformattedVersion = version.Substring(0, lastPeriodIndex);
through using an array, if that's what you really want:
string version = "1.0.420.50";
var numbers = version.Split(new char[]{'.'}, StringSplitOptions.RemoveEmptyEntries);
string reformattedVersion = numbers[0] + '.' + numbers[1] + '.' + numbers[2] + '.' + numbers[3];
but that's a much less elegant/quick solution.
Related
Solved, thanks for the help!
So I got an assignment for school, and no matter how much I search the net or read my books I can't figure out the answer to the question.
I have done programming for about 4 hours, so thats why the question is phrased wierdly, I think.
Console.WriteLine("Enter a number with any number of decimals.");
string input;
input = Console.ReadLine();
decimal myNumber = decimal.Parse(input);
Console.WriteLine("Please specify how many decimals you want to be shown.");
string input2;
input22 = Console.ReadLine();
int myDecimal = int.Parse(input2);
Console.WriteLine(("Your number with the choosen number of decimals: {0:f3}"), myNumber);
So, when I run it and enter 2,1234567 as my number and 5 as my number of decimals, it prints 2,123 instead of 2,12345.
I know it prints 3 decimals because of the 3 after the f, but I can't figure out how to change the 3 into the ammount chosen by the user.
I have tried {0:f(myDecimal)}, {myDecimal:f and {0:f(int = myDecimal)} , none of which I expected to work as I was just testing things out.
The answer is probably really simple, and I'm probably just overthinking things, but help would be very much appriciated!
You need a format-ception here:
// the {{ and }} escapes to { and }
var numberFormat = string.Format("{{0:f{0}}}", myDecimal).Dump();
Console.WriteLine("Your number with the choosen number of decimals: " + numberFormat, myNumber);
You can use ToString too
decimal myNumber = 224323.545656M;
int myDecimal = 4;
Console.WriteLine(String.Format("Your number with the choosen number of decimals: {0} " , myNumber.ToString("F" + myDecimal)));
You could just simply change your last Console.WriteLine() call to this:
Console.WriteLine("Your number with the choosen number of decimals: {0}",
myNumber.ToString("f" + input2));
The part that changes is: myNumber.ToString("f" + input2). What this does is use string concatenation to build your format string from your variable input2.
I made a fiddle here.
Please keep in mind though, the format string you are using ("F") will round to that number of decimal places (i.e 1.236 would become 1.24 with format "F2")
You need to build the format string dynamically. At this point using a substituted string is harder than ToString:
var digits = 3;
var input = 2.123456789;
var format = $"F{digits}";
var output = "Some text {input.ToString(format)} some more text";
This is a question around how the compiler/language deals with this.
Take the following code:
Console.WriteLine("Enter some numbers separated by ",");
var numbers = Console.ReadLine();
var splitNumber = numbers.Split(',');
var maxNumber = splitNumber.Max();
Console.WriteLine("highest is: " + maxNumber);
Entering a string such as "1,2,3,4,5" will output the 5 as the max number.
However, using "1,2,3,55,6" outputs 6. Whereas, "33,1,4,1" gives 4. Bizarrely, "33,1,2,3" gives 33.
I know there is a better/simpler/different way of doing this using a loop. I am totally missing something with how the compiler is treating these strings to determine the output. Can someone explain it? Or provide me a reference to look it up?
In string comparison, 6 > 55 returns True.
Do this instead, Split the string into an array using Split() Extension method and then use MAX() function which Returns the maximum value in a generic sequence available in LINQ
string x = "1,2,3,55,6";
var array = x.Split(',');
Console.WriteLine("highest is: " + array.Max(c => int.Parse(c)));
Output:
highest is: 55
The "max" string is the last string in lexicographical order, i.e. the order you would list them in a dictionary
You need to use e.g. int.Parse to convert your strings to a number type if you want the numeric maximum.
You need to compare the number as ints from a list or array.
var <int> Numbers = new List<int>();
while(String had not ended)
{
var splitNumber = (int) numbers.Split(',');
Numbers.Add(splitNumner);
}
var maxNumber = Numbers.Max();
Console.WriteLine("highest is: " + maxNumber);
You can do this, Convert the string array to an array of int using ConvertAll and then find the max
Console.WriteLine("Enter some numbers separated by ");
var numbers = Console.ReadLine();
var splitNumber = numbers.Split(',');
int[] myInts = Array.ConvertAll(splitNumber, int.Parse);
var maxNumber = myInts.Max();
Console.WriteLine("highest is: " + maxNumber);
I tried compiling your code with same inputs. I have also getting the same output but i thing when u try to perform .Max() operation on a string array it is only comparing the first character of each entries in your second array.
If the input is 1,2,3,55,6 you are gonna get the output as 6 because when you compare all the numbers and there first digit 6 is the largest. But if you change the input to 1,2,3,75,6 now you are gonna get the output as 75 because 7 is the biggest first digit of all the numbers in the list.
string str = "1,2,3,75,6";
var splitNumber = str.Split(',');
var maxNumber = splitNumber.Max();
Like all the other answers u need to convert the string array into an integer array and then apply it.
Ans for how the compiler is treating these strings to determine the output?:
As these are strings, string equality gets checked for it.
The compiler takes each string value and compares it to one by one char. It deduces equality on the first occurrence of mismatch (e.g. in 55 vs 6, 5 is less than 6, hence 55 is less than 6)
You can use this :
Console.WriteLine("Enter a series of number separated by comma and I will tell you which one is the biggest, cool!");
var input = Console.ReadLine().Split(',');
Console.WriteLine("Biggest is :" + input.Max(c => int.Parse(c)));
You can also do this:
var splitNumber = numbers.Split(',').Select(c=>Convert.ToInt32(c)).Max();
Console.WriteLine("highest is: " + splitNumber);
change Var to Int64
Int64 maxNumber = Int64.Parse(splitNumber.Max());
My reference number is "DTS00001" it is a String variable in C# program
i want to increment this number by one and the result should be like "DTS00002"
here is the code i tried,
while (reader.Read())
{
String str = reader["rfno"].ToString();
String st = str.Substring(3, 5);
int number = Convert.ToInt32(st);
number += 1;
string myNewString = "DTS" + number;
MessageBox.Show(myNewString);
The result doesn't contain the required leading zeros before the new number.
.
Homework or not, here's one way to do it. It's heavily influensed by stemas answer. It uses Regex to split the alphabetical from the numeric. And PadLeft to maintain the right number of leading zeroes.
Tim Schmelters answer is much more elegant, but this will work for other types of product-numbers as well, and is not limited to a specific number of leading zeros or a specific character set in the beginning. The downside with this solution is that it has to be [alphabetical][numerical].
private static string Increase(string productNo)
{
// This is a regex to split it into to groups.
var numAlpha = new Regex("(?<Alpha>[a-zA-Z]*[ _]?)(?<Numeric>[0-9]*)");
// Match the input string for the regex.
var match = numAlpha.Match(productNo);
// Get the alphabetical part.
var alpha = match.Groups["Alpha"].Value;
// Get the numeric part.
int num = int.Parse(match.Groups["Numeric"].Value);
// Add +1
num++;
// Combine the alphabetical part with the increased number, but use PadLeft to maintain the padding (leading zeros).
var newString = string.Format("{0}{1}", alpha, num.ToString().PadLeft(match.Groups["Numeric"].Value.Length, '0'));
return newString;
}
Console.WriteLine(Increase("DTS00008"));
Console.WriteLine(Increase("DTS00010"));
Console.WriteLine(Increase("DTS00020"));
Console.WriteLine(Increase("DTS00099"));
Console.WriteLine(Increase("PRODUCT0000009"));
Console.WriteLine(Increase("PRODUCT0000001"));
Output:
DTS00009
DTS00011
DTS00021
DTS00100
PRODUCT0000010
PRODUCT0000002
I need to display some numbers in a variable of type decimal.
I want to display them almost as they are, which ToString("G29") gives me.
However, I want to add a thousands separator. ToString("N") gives me the thousands separator but totally loses the "G29 goodness".
Is there a simple solution to get the display string I want?
value "N" "G29" What I Want
============= ========== ========== ==============
296018.413 296,018.41 296018.413 296,018.413
652609 652,609.00 652609 652,609
296.018413 296.02 296.018413 296.018413
326.305 326.31 326.305 326.305
Edit:
Another SO question/answer recently made me aware that "G29" returns values less than 0.0001 in scientific notation. So when I wrote the question I was unaware that the solution needed to handle special cases like these:
value What I Want
============ =============
0.00001 0.00001
12345.000067 12,345.000067
You might have to do a little bit of work around.
How about this?
decimal d = 34561.2223400M;
string decimalPart = (d - (int)d).ToString("G29");
string integerPart = d.ToString("##,###");
string finalNumber = integerPart + decimalPart.Substring(1,decimalPart.Length-1);;
There is a pretty simple solution to this, though it involves a fairly long format string.
decimal d = 12345.000067m;
string s = d.ToString("#,###0.############################"); // 28 #'s after the decimal
You have to format the string.
Try:
string yourString = String.Format("{0:N29}", yourWeight);
Edit:
The above was pretty close. This gives exactly the desired results:
string yourString = String.Format("{0:N29}", yourWeight).Trim(new [] { '0', '.' });
I have a string consist of integer numbers followed by "|" followed by some binary data.
Example.
321654|<some binary data here>
How do i get the numbers in front of the string in the lowest resource usage possible?
i did get the index of the symbol,
string s = "321654654|llasdkjjkwerklsdmv"
int d = s.IndexOf("|");
string n = s.Substring(d + 1).Trim();//did try other trim but unsuccessful
What to do next? Tried copyto but copyto only support char[].
Assuming you only want the numbers before the pipe, you can do:
string n = s.Substring(0, d);
(Make it d + 1 if you want the pipe character to also be included.)
I might be wrong, but I think you are under the impression that the parameter to string.Substring(int) represents "length." It does not; it represents the "start-index" of the desired substring, taken up to the end of the string.
s.Substring(0,d);
You can use String.Split() here is a reference http://msdn.microsoft.com/en-us/library/ms228388%28VS.80%29.aspx
string n = (s.Split("|"))[0] //this gets you the numbers
string o = (s.Split("|"))[1] //this gets you the letters