for example: if a string value is "123456.7890" .
if user enters the length 6 and the other value 2 for the decimal place.
the output value should be like "123456.78"
if user enters the length 5 and the other value 3 for the decimal place.
the output value should be like "12345.789"
string s = "123456.7890";
string a = string.Format("{0, 2:F2}", s);
int index = a.IndexOf('.');
a = a.Substring(index, (a.Length-index));
One approach could be like this:
NOTE: If the string's length is less than the number of characters you're taking, code will throw an exception ArgumentOutOfRangeException
int LeftPlaces = 4;
int RightPlaces = 2;
String Input = "123456.7890";
String[] Splitted = Input.Split('.');
String StrLeft = Splitted[0].Substring(0, LeftPlaces);
String StrRight = Splitted[1].Substring(0, RightPlaces);
Console.WriteLine(StrLeft + "." + StrRight);
Output: 1234.78
The most crude and direct way would be:
var length = 5;
var decimalPlaces = 2;
var s = "123456.7890";
var data = s.Split('.');
var output1 = data[0].Substring(0, length);
var output2 = data[1].Substring(0, decimalPlaces);
var result = output1 + "." + output2;
If you want to do this without strings, you can do so.
public decimal TrimmedValue(decimal value,int iLength,int dLength)
{
var powers = Enumerable.Range(0,10).Select(x=> (decimal)(Math.Pow(10,x))).ToArray();
int iPart = (int)value;
decimal dPart = value - iPart;
var dActualLength = BitConverter.GetBytes(decimal.GetBits(value)[3])[2];
var iActualLength = (int)Math.Floor(Math.Log10(iPart) + 1);
if(dLength > dActualLength || iLength > iActualLength)
throw new ArgumentOutOfRangeException();
dPart = Math.Truncate(dPart*powers[dLength]);
iPart = (int)(iPart/powers[iActualLength - iLength]);
return iPart + (dPart/powers[dLength]);
}
Client Call
Console.WriteLine($"Number:123456.7890,iLength=5,dLength=3,Value = {TrimmedValue(123456.7890m,5,3)}");
Console.WriteLine($"Number:123456.7890,iLength=6,dLength=2,Value = {TrimmedValue(123456.7890m,6,2)}");
Console.WriteLine($"Number:123456.7890,iLength=2,dLength=4,Value = {TrimmedValue(123456.7890m,2,4)}");
Console.WriteLine($"Number:123456.7890,iLength=7,dLength=3,Value = {TrimmedValue(123456.7890m,7,3)}");
Output
Number:123456.7890,iLength=5,dLength=3,Value = 12345.789
Number:123456.7890,iLength=6,dLength=2,Value = 123456.78
Number:123456.7890,iLength=2,dLength=4,Value = 12.789
Last call would raise "ArgumentOutOfRangeException" Exception as the length is more than the actual value
Related
Is there any way I could use a loop instead of writing out all of these if/else statements? I'm not sure if it is possible and I have looked online and haven't seen very many guides that would help me.
int numberOne = random.Next(id2) + 1;
int numberTwo = random.Next(id2) + 1;
int numberThree = random.Next(id2) + 1;
int numberFour = random.Next(id2) + 1;
int numberFive = random.Next(id2) + 1;
if (id1 == 1)
{
int total = numberOne;
string newmessage = "message";
return Json(newmessage);
}
else if(id1 == 2)
{
int total = numberOne + numberTwo;
string newmessage = "message";
return Json(newmessage);
}
else if (id1 == 3)
{
int total = numberOne + numberTwo + numberThree;
string newmessage = "message";
return Json(newmessage);
}
else if (id1 == 4)
{
int total = numberOne + numberTwo + numberThree + numberFour;
string newmessage = "message";
return Json(newmessage);
}
else if (id1 == 5)
{
int total = numberOne + numberTwo + numberThree + numberFive;
string newmessage = "message";
return Json(newmessage);
}
What you likely want to do is:
int total = Enumerable.Range(1, id1).Sum(z => random.Next(id2) + 1);
string newmessage = "message";
return Json(newmessage);
There is no need for an explicit loop (since Enumerable.Range will do the looping for you).
Since you probably need a loop and not using lambdas, you can go with something like this:
int total = 0;
for (int i = 0; i < id1; i++)
{
total += random.Next(id2) + 1;
}
return Json("message"); // I assume you want to return total here;
The reason this works is that if id1 is 1, you'd break out of the loop after doing 1 random.Next. If id2 is 2, then you'd run thru the first number and then add the 2nd number automatically. With this approach, you could support any number, not just up to 5.
I'd go with #mjwills solution, but here's an explanation of how you might do it in a step by step fashion:
The first thing I did was declare random, id1 and id2. I varied id1 during testing. When you post code, you should include this kind of thing, that way the folks help you don't have to reverse engineer what you are thinking:
var id1 = 5;
var id2 = 10;
var random = new Random();
Then, I realize that in each case, you have a chunk of the same code (the last two lines), so I extracted that duplicated code out and put it at the bottom of the loop (and I used NewtonSoft's JsonConvert class to convert things to JSON (which I'm assuming your Json function does) - I have that NuGetted into my test project):
string newMessage = "message";
return JsonConvert.SerializeObject(newMessage);
Finally, here's the loop you were asking about. I initialize total (I could put that initialization in the for loop, but it's clearer this way). Also note that the for loop is non-standard, it loops from 1 to N inclusive (generally for loops are 0 to N-1). This loop is between the initialization code and the final code:
var total = 0;
for (var i = 1; i <= id1; ++i)
{
total += (random.Next(id2) + 1);
}
What #mjwills code does is convert that into a single expression. The Enumerable.Range(1, id1) part generates a collection of consecutive integers starting at 1 and having id1 entries. Then he calls .Sum, passing it a lambda that represents a function to run on each item in the collection before it is summed. My loop basically does the same thing.
Altogether, it looks like this:
var id1 = 5;
var id2 = 10;
var random = new Random();
var total = 0;
for (var i = 1; i <= id1; ++i)
{
total += (random.Next(id2) + 1);
}
string newMessage = "message";
return JsonConvert.SerializeObject(newMessage);
try this, it also allows you init 5 numbers using any algoritm, not just the same
//var random=new Random();
//var id2=2;
//var id1=4;
var data = new int[]{
random.Next(id2) + 1,
random.Next(id2) + 1,
random.Next(id2) + 1,
random.Next(id2) + 1,
random.Next(id2) + 1
};
var total=0;
for ( var i = 0; i < id1; i++)
{
total+=data[i];
}
var newmessage = $"message#{id1.ToString()}, total {total.ToString()} ";
return Json(newmessage);
I got stuck in creating an algorithm that creates sets of 4 characters from two strings, two characters from one string and two from other string.
Example:
String one: FIRSTNAME
String two: LASTNAME
and the result that I expect is to get 10 sets of 4 characters like this: FILA, RSST, TNNA, AMME, EFLA and so on until we get 10 combinations like this.
this is the code that I made
using System;
public class Program
{
public static void Main()
{
Console.WriteLine("Name");
string name = Console.ReadLine();
Console.WriteLine("Lastname");
string lastname = Console.ReadLine();
int i;
var nchars = name.ToCharArray();
var pchars = lastname.ToCharArray();
for (i = 0; i <= 10; i++){
int ctr0;
int ctr;
int ctr2;
for (ctr = 0, ctr2 = 1, ctr0 = 1;
ctr < 10;
ctr0++, ctr = ctr + 2, ctr2 = ctr2 + 2) {
Console.WriteLine("{0}{1}{2}{3}{4}",
ctr0,
nchars[ctr],
nchars[ctr2],
pchars[ctr],
pchars[ctr2]);
}
}
}
}
and the output is good so far because I get
1FILA
2RSST
3TNNA
4AMME
but it stops when the string ends and instead of getting 10 combinations I get only 4.. what can I do?
Am I doing it wrong?
Or adding some Enumerable love.
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Name");
string name = Console.ReadLine();
Console.WriteLine("Lastname");
string lastname = Console.ReadLine();
// set the number of required sets and size
const int sets = 10;
const int size = 2;
// make both inputs long enough
var input1 = string.Concat(Enumerable.Repeat(name, (Math.Abs((sets * size) / name.Length) + 1)));
var input2 = string.Concat(Enumerable.Repeat(lastname, (Math.Abs((sets * size) / lastname.Length) + 1)));
// enumerate the index so we can substring the inputs.
var results = Enumerable.Range(0, sets)
.Select(x => $"{x + 1}{input1.Substring(x * size, size)}{input2.Substring(x * size, size)}");
// optional write to console
foreach(var result in results)
{
Console.WriteLine(result);
}
}
}
Trying to rectify your alogrithm, I think this is what you should try:
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Name");
string name = "FIRSTNAME";
Console.WriteLine("Lastname");
string lastname = "LASTNAME";
int i;
var nchars = name.ToCharArray();
var pchars = lastname.ToCharArray();
var ncharsCount = nchars.Length;
var pcharsCount = pchars.Length;
//for (i=0;i<=10;i++){
int ctr0;
int ctr;
int ctr2;
for (ctr = 0, ctr2 = 1, ctr0=1; ctr0 < 10 ;ctr0++, ctr++,ctr2++){
Console.WriteLine("{0}{1}{2}{3}{4}", ctr0,nchars[ctr%ncharsCount],nchars[ctr2%ncharsCount],pchars[ctr%pcharsCount],pchars[ctr2%pcharsCount]);
}
//}
}
}
Let's split the initial problem into several easier ones:
CircularSubstring, e.g. for value = "12345", index = 4, length = 3 we get "512"
MyGemerator which generate "FILA", "RSST" etc.
Final output in the required format
Code:
private static String CircularSubstring(string value, int index, int length) {
StringBuilder sb = new StringBuilder(length);
// + + value.Length) % value.Length -
// .Net can return negative remainder when we want it to be in [0..value.Length)
for (int i = 0; i < length; ++i)
sb.Append(value[((index + value.Length + i) % value.Length + value.Length) % value.Length]);
return sb.ToString();
}
private static IEnumerable<string> MyGenerator(string left, string right, int size) {
for (int i = 0; ; i += size)
yield return CircularSubstring(left, i, size) + CircularSubstring(right, i, size);
}
Then we are ready to generate a report in required format:
string one = "FIRSTNAME";
string two = "LASTNAME";
int size = 2; // chunks of size 2 from each (one, two) strings
int take = 10; // 10 chunks to generate
string report = string.Join(Environment.NewLine, MyGenerator(one, two, size)
.Take(take)
.Select((item, index) => $"{index + 1}{item}")
);
Console.Write(report);
Outcome:
1FILA
2RSST
3TNNA
4AMME
5EFLA
6IRST
7STNA
8NAME
9MELA
10FIST
More demo:
Console.Write(string.Join(Environment.NewLine, MyGenerator("Stack", "Overflow", 3)
.Take(12)
.Select((item, index) => $"{index + 1,2}. {item}")
));
Outcome:
1. StaOve
2. ckSrfl
3. tacowO
4. kStver
5. ackflo
6. StawOv
7. ckSerf
8. taclow
9. kStOve
10. ackrfl
11. StaowO
12. ckSver
I am a big fan of the new $"" notation to format strings in c#. Hence I would like to use this notation to pre-pend some leading zero's to an integer.
var i = 10;
var s = $"{i:D4}";
This does the job well en results in 0010.
But what if the amount of zero's or the total length is variable. How do I accomplish that using this new notation ?
I'm looking for somthing like :
var TotalLength = 4; // IRL it would be a calculated value.
var format = "D" + TotalLength.ToString();
var i = 10;
var s = $"{i:format}";
variant I've tried but does not work either.
$"{i:{format}}"
Any suggestions ?
Or - mixing your something like and Rob's method:
var TotalLength = 4; // IRL it would be a calculated value.
var format = TotalLength.ToString("'D'0");
var i = 10;
var s = $"{i.ToString(format)}";
Based on the suggestions given I've made two extension methods :
public static String GetDnFormat(this int i)
{
return ((int)Math.Log10(i) + 1).ToString("'D'0");
}
public static String ToDnFormat(this int i, int source)
{
var format = source.GetDnFormat();
return i.ToString(format);
}
Usage :
var Page = 10;
var PageCount = 124;
var PageLabel = $"{Page.ToDnFormat(PageCount)}/{PageCount}"; // result : 010/124
I need to get value of below string into 2 variables.
Input
6.3-full-day-care
Expected output:
var price=6.3; //The input is dynamic.Cannot get fixed length
var serviceKey="full-day-care";
How can I do that? Substring doesn't help here.
You can use String.Split and String.Substring methods like;
string s = "6.3-full-day-care";
int index = s.IndexOf('-'); //This gets index of first '-' character
var price = s.Substring(0, index);
var serviceKey = s.Substring(index + 1);
Console.WriteLine(price);
Console.WriteLine(serviceKey);
Output will be;
6.3
full-day-care
Here a DEMO.
you can do like:
var val = "6.3-full-day-care";
var index = val.IndexOf("-"); //first occuarance of -
var price =double.Parse(val[index]);
var serviceKey = val.Substring(index);
Just to give idea. It's beter naturally use double.TryParse(..) on price
double price = 0;
double.TryParse(val[index], out prince, System.Globalization.InvariantCulture);
This should work
var s = "6.3-full-day-care";
var index = s.IndexOf('-');
var price = s.Substring(0, index);
var serviceKey = s.Substring(index + 1);
If the price and the key are always separated with a '-':
string s = "6.3-full-day-care";
int separatorIdx = s.IndexOf( '-' ); // get idx of first '-'
// split original string
string price = s.Substring( 0, separatorIdx );
string serviceKey = s.Substring( separatorIdx+1, s.Length );
Use String.Split with a maximum count http://msdn.microsoft.com/en-us/library/c1bs0eda.aspx
string s = "6.3-full-day-care";
string[] parts = s.split(new char[]{'-'}, 1);
var price = parts[0];
var serviceKey = parts[1];
I have strings that look like "01", "02". Is there an easy way that I can change the string into a number, add 1 and then change it back to a string so that these strings now look like "02", "03" etc. I'm not really good at C# as I just started and I have not had to get values before.
To get from a string to an integer, you can youse int.Parse():
int i = int.Parse("07");
To get back into a string with a specific format you can use string.Format():
strings = string.Format("{0:00}",7);
The latter should give "07" if I understand http://www.csharp-examples.net/string-format-int/ correctly.
You can convert the string into a number using Convert.ToInt32(), add 1, and use ToString() to convert it back.
int number = Convert.ToInt32(originalString);
number += 1;
string newString = number.ToString();
Parse the integer
int i = int.Parse("07");
add to your integer
i = i + 1;
make a new string variable and assign it to the string value of that integer
string newstring = i.ToString();
AddStringAndInt(string strNumber, int intNumber)
{
//TODO: Add error handling here
return string.Format("{0:00}", (int.TryParse(strNumber) + intNumber));
}
static string StringsADD(string s1, string s2)
{
int l1 = s1.Count();
int l2 = s2.Count();
int[] l3 = { l1, l2 };
int minlength = l3.Min();
int maxlength = l3.Max();
int komsu = 0;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < maxlength; i++)
{
Int32 e1 = Convert.ToInt32(s1.PadLeft(maxlength, '0').ElementAt(maxlength - 1 - i).ToString());
Int32 e2 = Convert.ToInt32(s2.PadLeft(maxlength, '0').ElementAt(maxlength - 1 - i).ToString());
Int32 sum = e1 + e2 + komsu;
if (sum >= 10)
{
sb.Append(sum - 10);
komsu = 1;
}
else
{
sb.Append(sum);
komsu = 0;
}
if (i == maxlength - 1 && komsu == 1)
{
sb.Append("1");
}
}
return new string(sb.ToString().Reverse().ToArray());
}
I needed to add huge numbers that are 1000 digit. The biggest number type in C# is double and it can only contain up to 39 digits. Here a code sample for adding very huge numbers treating them as strings.