If you take a look at the plastic in your wallet the 16 digit credit card number is broken into 4 groups of 4. Im trying to do the same thing,
Currently I have a string that has 16 digits but is formed as 1 single number. How can I add a " " after the 4th 8th & 12th number?
Any tips would be really helpful.
Thanks
var number = 1234567890123456;
number.ToString( "0000-0000-0000-0000" );
Try something similar to this answer, using a NumberFormatInfo:
NumberFormatInfo format = new NumberFormatInfo();
format.NumberGroupSeparator = " ";
format.NumberGroupSizes = new[] { 4 };
format.NumberDecimalDigits = 0;
Use as:
long number = 7314787188619939;
string formatted = number.ToString("n", format);
Console.WriteLine(formatted);
Or, if you're dealing with a string, you may choose can use a regex for a quick string manipulation. This will be easy to adapt to other characters:
string str = "7314787188619939";
str = Regex.Replace(str, "(?!^).{4}", " $0" ,RegexOptions.RightToLeft);
string number = "1234567890ABCDEF";
int counter = 0;
var result = number
.GroupBy(_ => counter++ / 4)
.Select(g => new String(g.ToArray()));
There are many answers. Given a string s=1234567890123456 the easiest might be to create a StringBuilder and append it. Untested code example below.
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.Length; i += 4)
{
sb.append(s.Substring(i, 4)); // Append these 4
if (i != s.Length - 4)
sb.append(" "); // append a space for all but the last group
}
Console.WriteLine(sb.ToString());
You may try something like this, an extension method
public static IEnumerable<String> SplitToParts(this String forSplit, Int32 splitLength)
{
for (var i = 0; i < forSplit.Length; i += splitLength)
yield return forSplit.Substring(i, Math.Min(splitLength, forSplit.Length - i));
}
string s ="1234123412341234";
s.SplitToParts(4) should do the trick
Hope this works !
Or if working with MD5 hashes, you could use an implementation like so...
public string exHashMd5(string data)
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(data));
byte[] result = md5.Hash;
StringBuilder str = new StringBuilder();
for (int i = 0; i < result.Length; i++)
{
str.Append(result[i].ToString("X2"));
}
/// The implementation like so. (Below)
NumberFormatInfo format = new NumberFormatInfo();
format.NumberGroupSeparator = " ";
format.NumberGroupSizes = new[] { 8 };
format.NumberDecimalDigits = 0;
string rstr = str.ToString();
rstr = Regex.Replace(rstr, "(?!^).{8}", " $0", RegexOptions.RightToLeft);
return rstr.ToString();
/// At the end you get yourself a nice 4 way split.
/// Test it out. have a go with chucking it into a
/// MessageBox.Show(exHashMd5("yourstring"));
}
/// Could even go one further and add
string hashtext;
string newline = Enviroment.Newline;
hashtext = exHashMd5("yourtext");
/// Then you do a simple command.
MessageBox.Show(hashtext + newline + hashtext);
/// Nice four way again. complex but yet made simple.
To work out what you need it to do, use maths. seriously, its mathematical. divide the amount of characters, till you are able to get a sum that equals four. for example, 32 / 8 = 4. then this will give you the four way split you need. basic maths. basic. basic. basic.
Related
I have written this piece of code:
int i = 0;
br.BaseStream.Position = i;
armorvalues[i] = br.ReadBytes(0x000E91D4);
string[] outbyte= new string[0x000E91D4];
for (int j=0; j < 0x000E91D4; j++)
{
outbyte[j] = Convert.ToString(String.Format("{0:X2}", armorvalues[0][j]));
}
Now since this is an array and I want to some algorithmic operations on the whole data, I need to convert it into a string. i need to append it in a single string. What should I do?
Not sure why you want to do so, maybe if you explain better your need then it'll be good. But for your question:
You can use string.Join:
var strValue = string.Join(" ", outbyte);
And instead of doing it after the look you can also:
var strValue = string.Join(" ", armorvalues[0].Select(item => String.Format("{0:X2}", item)));
Take a look at the StringBuilder class
StringBuilder sb = new StringBuilder(0x000E91D4*2); // length * 2 since every byte is going to be represented by 2 chars
for (int j=0; j < 0x000E91D4; j++)
{
sb.Append(Convert.ToString(String.Format("{0:X2}", armorvalues[0][j])));
}
string yourString = sb.ToString();
Edit:
I was not aware of that string.Join overload that takes an IEnumerable, that it more elegant, go with Gilad Green's solution or if you don't want the values be separated by an empty space (" ") just do
string output = string.Concat(armorvalues[0].Select(item => String.Format("{0:X2}", item)));
I need to convert numbers into a comma separated format to display in C#.
For Example:
1000 to 1,000
45000 to 45,000
150000 to 1,50,000
21545000 to 2,15,45,000
How to achieve this in C#?
I tried the below code:
int number = 1000;
number.ToString("#,##0");
But it is not working for lakhs.
I guess you can do this by creating a custom number format info for your needs
NumberFormatInfo nfo = new NumberFormatInfo();
nfo.CurrencyGroupSeparator = ",";
// you are interested in this part of controlling the group sizes
nfo.CurrencyGroupSizes = new int[] { 3, 2 };
nfo.CurrencySymbol = "";
Console.WriteLine(15000000.ToString("c0", nfo)); // prints 1,50,00,000
if specifically only for numbers then you could also do
nfo.NumberGroupSeparator = ",";
nfo.NumberGroupSizes = new int[] { 3, 2 };
Console.WriteLine(15000000.ToString("N0", nfo));
Here's a similar thread to yours add commas in thousands place for a number
and here's the solution that worked perfectly for me
String.Format("{0:n}", 1234);
String.Format("{0:n0}", 9876); // no decimals
If you want to be unique and do extra work that you don't have to here is a function I created for integer numbers you can place commas at whatever interval you want, just put 3 for a comma for each thousandths or you could alternatively do 2 or 6 or whatever you like.
public static string CommaInt(int Number,int Comma)
{
string IntegerNumber = Number.ToString();
string output="";
int q = IntegerNumber.Length % Comma;
int x = q==0?Comma:q;
int i = -1;
foreach (char y in IntegerNumber)
{
i++;
if (i == x) output += "," + y;
else if (i > Comma && (i-x) % Comma == 0) output += "," + y;
else output += y;
}
return output;
}
Have you tried:
ToString("#,##0.00")
Quick and dirty way:
Int32 number = 123456789;
String temp = String.Format(new CultureInfo("en-IN"), "{0:C0}", number);
//The above line will give Rs. 12,34,56,789. Remove the currency symbol
String indianFormatNumber = temp.Substring(3);
An easy solution would be to pass a format into the ToString() method:
string format = "$#,##0.00;-$#,##0.00;Zero";
decimal positiveMoney = 24508975.94m;
decimal negativeMoney = -34.78m;
decimal zeroMoney = 0m;
positiveMoney.ToString(format); //will return $24,508,975.94
negativeMoney.ToString(format); //will return -$34.78
zeroMoney.ToString(format); //will return Zero
Hope this helps,
I have a number that I store in string because it is a long number and I want to convert it to binary format.
string number = "25274132531129322906392322409257377862778880"
I want to get:
string binresult;
that holds value:
0000000000000001001000100010001000000000000000100000001011101000000000000000000011110000000000000000110100000000000000100000000000000000000000000000000000000000
You actually can use Dan Byström's answer to How to convert a gi-normous integer (in string format) to hex format? (C#), like Michael Edenfeld suggested in the comments. It will get you from your large number string to hexadecimal. I will repost his code for your convenience:
var s = "25274132531129322906392322409257377862778880";
var result = new List<byte>();
result.Add(0);
foreach (char c in s)
{
int val = (int)(c - '0');
for (int i = 0 ; i < result.Count ; i++)
{
int digit = result[i] * 10 + val;
result[i] = (byte)(digit & 0x0F);
val = digit >> 4;
}
if (val != 0)
result.Add((byte)val);
}
var hex = "";
foreach (byte b in result)
hex = "0123456789ABCDEF"[b] + hex;
I won't profess to understand how he came up with this, but I have tested it with a few numbers that I know the hex values for, and it appears to work. I'd love to hear an explanation from him.
Now, you want your answer in binary, and luckily for you, converting from hexadecimal to binary is one of the easier things in life. Every hex value converts directly to its 4-bit binary counterpart (0x7 = 0111, 0xA = 1010, etc). You could write a loop to perform this conversion character by character, but Guffa's answer to C# how convert large HEX string to binary provides this handy dandy Linq statement to perform the same action:
string binaryString = string.Join(string.Empty,
hex.Select(c => Convert.ToString(Convert.ToInt32(
c.ToString(), 16), 2).PadLeft(4, '0')));
Running all of this together gives me:
01110001010101010100100000000000110010010010001010100000000000000101110111000000000001010001010000000000110001111111111111111111111111111111111011100010
For your number. I don't know how you plan to verify it, but if Dan's hex translation is right, then that binary string will definitely be right.
System.Convert can help you with bits and pieces like this. See below.
string decString = "12345";
int integer = Convert.ToInt32(decString);
string binString = Convert.ToString(integer, 2);
You can try this:
string number = "25274132531129322906392322409257377862778880";
char[] strArr = number.ToCharArray();
StringBuilder sb = new StringBuilder();
foreach (char chr in strArr)
{
sb.Append(Convert.ToString((int)Char.GetNumericValue(chr), 2));
}
string binresult = sb.ToString();
I have a string composed of 16 digits (a hexadecimal number), which will be entered in a textbox as one large number. For example, '1111222233334444".
I need to
read this number in,
divide it into four groups, such as 1111 2222 3333 4444.
store the groups into four variables, or an array
I have found some methods to do this, but they just write to console. So after the user enters that data, I need to have something like:
string first = 1111;
string second = 2222;
string third = 3333;
string fourth = 4444.
Any help is appreciated!
You can do it with substring.
string strNumber = "1111222233334444";
string []strArr = new string[4];
for(int i=0; i < 4; i++)
{
strArr[i] = strNumber.Substring(i*4, 4);
}
Here it is:
string initial_string = TextBox1.Text; //read from textbox
string [] number = new string[4];
number[0] = initial_string.Substring(0,4);
number[1] = initial_string.Substring(4,4);
number[2] = initial_string.Substring(8,4);
number[3] = initial_string.Substring(12,4);
You can use Regex to do it in a single line:
var res = Regex.Split(str, "(?<=\\G\\d{4})");
NOTE: This works fine under Microsoft .NET, but does not work with Mono's implementation of Regex.
I am having the numbers follows taken as strings
My actual number is 1234567890123456789
from this i have to separate it as s=12 s1=6789 s3=3456789012345
remaining as i said
I would like to add as follows
11+3, 2+4, 6+5, 7+6, 8+7, 9+8 such that the output should be as follows
4613579012345
Any help please
public static string CombineNumbers(string number1, string number2)
{
int length = number1.Length > number2.Length ? number1.Length : number2.Length;
string returnValue = string.Empty;
for (int i = 0; i < length; i++)
{
int n1 = i >= number1.Length ? 0 : int.Parse(number1.Substring(i,1));
int n2 = i >= number2.Length ? 0 : int.Parse(number2.Substring(i,1));
int sum = n1 + n2;
returnValue += sum < 10 ? sum : sum - 10;
}
return returnValue;
}
This sounds an awful lot like a homework problem, so I'm not giving code. Just think about what you need to do. You are saying that you need to take the first character off the front of two strings, parse them to ints, and add them together. Finally, take the result of the addition and append them to the end of a new string. If you write code that follows that path, it should work out fine.
EDIT: As Ralph pointed out, you'll also need to check for overflows. I didn't notice that when I started typing. Although, that shouldn't be too hard, since you're starting with a two one digit numbers. If the number is greater than 9, then you can just subtract 10 to bring it down to the proper one digit number.
How about this LINQish solution:
private string SumIt(string first, string second)
{
IEnumerable<char> left = first;
IEnumerable<char> right = second;
var sb = new StringBuilder();
var query = left.Zip(right, (l, r) => new { Left = l, Right = r })
.Select(chars => new { Left = int.Parse(chars.Left.ToString()),
Right = int.Parse(chars.Right.ToString()) })
.Select(numbers => (numbers.Left + numbers.Right) % 10);
foreach (var number in query)
{
sb.Append(number);
}
return sb.ToString();
}
Tried something:
public static string NumAdd(int iOne, int iTwo)
{
char[] strOne = iOne.ToString().ToCharArray();
char[] strTwo = iTwo.ToString().ToCharArray();
string strReturn = string.Empty;
for (int i = 0; i < strOne.Length; i++)
{
int iFirst = 0;
if (int.TryParse(strOne[i].ToString(), out iFirst))
{
int iSecond = 0;
if (int.TryParse(strTwo[i].ToString(), out iSecond))
{
strReturn += ((int)(iFirst + iSecond)).ToString();
}
}
// last one, add the remaining string
if (i + 1 == strOne.Length)
{
strReturn += iTwo.ToString().Substring(i+1);
break;
}
}
return strReturn;
}
You should call it like this:
string strBla = NumAdd(12345, 123456789);
This function works only if the first number is smaller than the second one. But this will help you to know how it is about.
In other words, you want to add two numbers treating the lesser number like it had zeroes to its right until it had the same amount of digits as the greater number.
Sounds like the problem at this point is simply a matter of finding out how much you need to multiply the smaller number by in order to reach the number of digits of the larger number.