Padding not being applied to string - c#

Hi I am just trying to add a zero to a number that is a string, for example, a company has some old barcodes in the system that was printed with only 12 characaters their new barcodes is 13 I just simply have to add an extra zero when its 12 in length.
using System;
public class Program
{
public static void Main()
{
string BarCode="000001661705";
char pad = '0';
if(BarCode.Length==12)
{
BarCode = BarCode.PadLeft(1, pad);
}
Console.WriteLine("Length of barcode" + BarCode.Length);
Console.WriteLine("Barcode=" + BarCode);
}
}
Here is the .net fillddle you will see the number of characters is still 12 when it should be 13 with the added zero on it.
https://dotnetfiddle.net/VsvPIl

Just add it as a string?
using System;
public class Program
{
public static void Main()
{
string BarCode="000001661705";
char pad = '0';
if(BarCode.Length==12)
{
BarCode = pad + BarCode;
}
Console.WriteLine("Length of barcode" + BarCode.Length);
Console.WriteLine("Barcode=" + BarCode);
}
}

You have to use BarCode.PadLeft(BarCode.Length + 1, pad) to get the desired output.
But I don't understand why you would want to do that, just add "0" + BarCode

PadLeft accepts as an argument totalWidth of returned string, so it pads if string is shorter and does nothing when length is already equal to o greater. Just use:
BarCode = BarCode.PadLeft(13, pad);
instead of
if(BarCode.Length==12)
{
// here is the problem, you specified totalWidth = 1
BarCode = BarCode.PadLeft(1, pad);
}
String.PadLeft Method

Related

How to create qr code in tlv (tag, length, value) format in c# windows application

i want to create a qr code with five tlv data.
Sellers name
Vat number
Datetime
Invoice total
Vat amount
I need this for vat bill of Saudi arabia. I want to implement this in five steps
Create tlv data
Convert to hex representation
Convert to string
Convert to base64 string
Create qr code bitmap image.
Any helps will be appreciated
Hi We have completed and created a DEMO program to understand ( I am using c# for my demonstration)
See my Code and you should understand
1 ) Define the function to convert each TAG to hex bypassing the Tag No and TAG Value and returning the HEX Value
public static String text2hex(Int32 Tagnum, String TagVal)
{
string hexval = text2hex(TagVal);
string hextag = decToHexa(Tagnum);
string hexlen = decToHexa(TagVal.Length);
return (hextag + hexlen + hexval);
}
2 ) Define a function to pass the HEX value and return a BASE64 Encoded Value
public static String HexToBase64(string strInput)
{
var bytes = new byte[strInput.Length / 2];
for (var i = 0; i < bytes.Length; i++)
{
bytes[i] = Convert.ToByte(strInput.Substring(i * 2, 2), 16);
}
return Convert.ToBase64String(bytes);
}
3 ) convert all tags and tag values and concatenate them (TLV Format)
string Hexcode = text2hex(1, CompName) + text2hex(2, Vatno) + text2hex(3, datetimetax) + text2hex(4, amountTotal) + text2hex(5, amountVat);
once you have the HEXcode of the value joined convert them to base64
string HextoBase = Base64StringEncode(Hexcode)
Convert the Base64 to QR Code
Reference Document
enter image description here
Found the issue for the Arabic. The Length for Latin text is the same in regular and utf8 mode, however for arabic, it will be different. so when producing the TLV, the L should be the length of the text after conversion to UTF8. So improving the answer above to:
public static String GetTLV(Int32 Tagnum, String TagVal)
{
return GetTLV(Tagnum, Encoding.UTF8.GetBytes(TagVal).Length, TagVal);
}
public static String GetTLV(Int32 Tagnum, int TagLen, String TagVal)
{
string hexval = text2hex(TagVal);
string hextag = decToHexa(Tagnum);
string hexlen = decToHexa(TagLen);
return (hextag + hexlen + hexval);
}
private static string text2hex(string tagVal)
{
byte[] ba = Encoding.UTF8.GetBytes(tagVal);
return BitConverter.ToString(ba).Replace("-","");
}
private static string decToHexa(int tagnum)
{
return tagnum.ToString("X2").Replace("-", "");
}

Converting Decimal to Binary C# using functions

I want to make a converter for decimal to binary using a function but I don't see what is wrong with my code: (the errors states that i can not simplicity convert string to char but I have converted it in line 12). Edit - I am interested in the process of converting denary to binary rather than the output.
static void Main (string[] args)
{
Console.WriteLine("Decimal 14 = Binary " + dec_to_bin(14));
Console.WriteLine("Decimal 100 = Binary " + dec_to_bin(100));
Console.WriteLine("Decimal 32 = Binary " + dec_to_bin(32));
Console.WriteLine("Decimal 64 = Binary " + dec_to_bin(64));
Console.ReadLine();
}
public static string dec_to_bin(int dec)
{
string binary = "11111111";
char[]binaryArray = binary.ToCharArray();
for (int i = 0; i < 8; i++)
{
if (dec % 2 == 0)
{
binaryArray[i] = "0"; // error 1
}
else
{
binaryArray[i] = "1"; // error 2
}
}
binary = new string(binaryArray);
return binary;
}
binaryArray[i] = "0" must be binaryArray[i] = '0'
"0" is a string literal while '0' is a char and you have an array of char.
Same for binaryArray[i] = "1"
While the above will solve your problem, I recommend using Convert.ToString(dec, 2) (as suggested by the dupe marked by mjwills). Of course, this makes only sense if you are interested in the outcome rather than in coding it yourself.
Mind that I deliberately did not address any other issues with the code snippet.

Different pattern to give input in console application

I am a beginner in .net and I made a simple console application and it's works. My problem is when I give input the input must be in new line
eg:
1
2
3
how I input like
1 2
3
I am using the following code
int a, b, c,d;
Console.WriteLine("Enter the numbers:");
a = Convert.ToInt32(Console.ReadLine());
b = Convert.ToInt32(Console.ReadLine());
c = Convert.ToInt32(Console.ReadLine());
d = a + b + c;
Console.WriteLine("Sum:" + d);
Write an input parser... ReadLine, split the resulting string by space character and feed each segment into int converter and sum them.
Example given below is taking advantage of Linq which is a bit functional and allow chaining something like the token array resulting from the split and performs operations on each of its elements. I.e. Select(...) is basically a map function that will apply Convert.ToInt32 to each elements in the token array and then pipe that into the Aggregate function that memoize the result so far (starting from 0 and keep adding the next element in the now converted int token array ... represented by s + t where s is current memoized seed and t is the current token in the iteration.)
using System;
using System.Linq;
public class Program
{
public static void Main()
{
var str = Console.ReadLine();
var tokens = str.Split(' ');
var result = tokens.Select(t => Convert.ToInt32(t)).Aggregate(0, (s, t) => s + t);
Console.WriteLine(result);
}
}
For completeness sake... This second version should be more resistant to error:
using System;
using System.Linq;
public class Program
{
public static void Main()
{
Console.WriteLine("Enter 1 or more numbers separated by space in between. I.e. 1 2\nAny non numerical will be treated as 0:");
var str = Console.ReadLine();
if (string.IsNullOrWhiteSpace(str))
{
Console.WriteLine("Sorry, expecting 1 or more numbers separated by space in betwen. I.e. 5 6 8 9");
}
else
{
var tokens = str.Split(' ');
var result = tokens
.Select(t =>
{
int i;
if (int.TryParse(t, out i))
{
Console.WriteLine("Valid Number Detected: {0}", i);
};
return i;
})
.Aggregate(0, (s, t) => s + t);
Console.WriteLine("Sum of all numbers is {0}", result);
}
Console.ReadLine();
}
}
You are using Console.ReadLine() which reads the whole line.
Documentation:
A line is defined as a sequence of characters followed by a carriage return (hexadecimal 0x000d), a line feed (hexadecimal 0x000a), or the value of the Environment.NewLine property. The returned string does not contain the terminating character(s).
You can read whole line and then process it, for example with String.Split method.
One option would be to accept a single line of input as a string and then process it. For example:
//Read line, and split it by whitespace into an array of strings
//1 2
string[] tokens = Console.ReadLine().Split();
//Parse element 0
int a = int.Parse(tokens[0]);
//Parse element 1
int b = int.Parse(tokens[1]);
One issue with this approach is that it will fail (by throwing an IndexOutOfRangeException/ FormatException) if the user does not enter the text in the expected format. If this is possible, you will have to validate the input.
For example, with regular expressions:
string line = Console.ReadLine();
// If the line consists of a sequence of digits, followed by whitespaces,
// followed by another sequence of digits (doesn't handle overflows)
if(new Regex(#"^\d+\s+\d+$").IsMatch(line))
{
... // Valid: process input
}
else
{
... // Invalid input
}
Alternatively:
Verify that the input splits into exactly 2 strings.
Use int.TryParse to attempt to parse the strings into numbers.
Here's an exmaple :
class Program
{
private static void Main(string[] args)
{
int a = 0,
b = 0;
Console.WriteLine("Enter the numbers:");
var readLine = Console.ReadLine();
if (readLine != null)
{
// If the line consists of a sequence of digits, followed by whitespaces,
// followed by another sequence of digits (doesn't handle overflows)
if (new Regex(#"^\d+\s+\d+$").IsMatch(readLine))
{
string[] tokens = readLine.Split();
//Parse element 0
a = int.Parse(tokens[0]);
//Parse element 1
b = int.Parse(tokens[1]);
}
else
{
Console.WriteLine("Please enter numbers");
}
}
var c = Convert.ToInt32(Console.ReadLine());
var d = a + b + c;
Console.WriteLine("Sum:" + d);
}
}

Index was outside the bounds of the array c#

I get the error of "Index was outside the bounds of the array", at this line " order.price = Convert.ToDouble(custOrder.Split('$')[1]); ", I have follow the video at here, http://www.youtube.com/watch?v=EbrGoUqbb-A, but I still get the error, I am newbie for C#
public struct Orders
{
public string item;
public double price;
}
const double TAX=0.06;
Orders order = new Orders();
static double subtotal=0;
static double totalTaxes=0;
static double total;
string finalBill = "FINAL BILL:\n";
private void getValues(string custOrder)
{
order.item = custOrder.Split('$')[0];
order.price = Convert.ToDouble(custOrder.Split('$')[1]);
listOutput.Items.Add("Price:" + order.price);
finalBill += "Ordered Item:" + order.item + "\nPrice:" + order.price.ToString("C2") + "\n";
updateBill();
}
private void updateBill()
{
subtotal += order.price;
total += order.price + (order.price * TAX);
totalTaxes += order.price * TAX;
listOutput.Items.Clear();
listOutput.Items.Add(finalBill);
listOutput.Items.Add("Subtotal:" + subtotal.ToString("C2"));
listOutput.Items.Add("Tax:" + totalTaxes.ToString("C2"));
listOutput.Items.Add("Total:" + total.ToString("C2"));
}
private void dropdownSelection(object sender, EventArgs e)
{
if (sender == comboBox1)
getValues(comboBox1.SelectedItem.ToString());
}
custOrder.Split('$')[1]
Stuff that into a variable and use your debugger. Looks like your string custOrder does not contain a '$' character, or it is the last character in the string.
the .Split method, when used on a string, it returns an array. The split parameter is a character that is used as the splitting point.
For example:
String x = "test$one";
var result = x.Split('$') // this returns an array ["test", "one"]
the arrays start their counting from zero, so
result[0] // is "test"
result[1] // is "one"
the splitting character is not included.
In your case, there is no dollar sign, so the split result will be an array with just one string, with the index 0. custOrder.Split('$')[1] does not exist.
Update your getValue method as follows
Check whether you split call really returns 2 array elements to get element of index=1.
Also check whether the returned value of index=1 is really of type double or not. else you will get another error for the string like "asdf$gf" or "asdf$"
private void getValues(string custOrder)
{
double num;
if (custOrder.Split('$').Count() > 1)
{
order.item = custOrder.Split('$')[0];
if (double.TryParse(custOrder.Split('$')[1], out num))
{
order.price = Convert.ToDouble(custOrder.Split('$')[1]);
listOutput.Items.Add("Price:" + order.price);
finalBill += "Ordered Item:" + order.item + "\nPrice:" + order.price.ToString("C2") + "\n";
updateBill();
}
}
}
your string does not contain the '$' text or it only contains 1 of them. try this instead:
string[] splits = custOrder.Split("$".ToCharArray());
if (1 == splits.Length)
order.item = Convert.ToDouble(splits[0]);
else
throw new Exception("Cannot find $ in the customer order");
Depending on what you want you also may have meant Convert.ToDouble(splits[0]); as arrays use zero based indexing not 1 based indexing.
EDIT: changed code based on questioner providing input data sample.

Increment a string with both letters and numbers

I have a string which i need to increment by 1 The string has both characters and numeric values.
The string layout i have is as follows "MD00494"
How would i increment this to "MD00496" & "MD00497" ect
If it was a normal string with numbers i would parse it to an int.
I have tried the following
int i = int.Parse(sdesptchNo);
i++;
txtDispatchNo.Text = i.ToString();
Anyone any ideas how i would go about this.
You first should figure out any commonality between the strings. If there is always a prefix of letters followed by digits (with a fixed width) at the end, then you can just remove the letters, parse the rest, increment, and stick them together again.
E.g. in your case you could use something like the following:
var prefix = Regex.Match(sdesptchNo, "^\\D+").Value;
var number = Regex.Replace(sdesptchNo, "^\\D+", "");
var i = int.Parse(number) + 1;
var newString = prefix + i.ToString(new string('0', number.Length));
Another option that might be a little more robust might be
var newString = Regex.Replace(x, "\\d+",
m => (int.Parse(m.Value) + 1).ToString(new string('0', m.Value.Length)));
This would replace any number in the string by the incremented number in the same width – but leaves every non-number exactly the same and in the same place.
Here is one Non-Regex way :P
string str = "MD00494";
string digits = new string(str.Where(char.IsDigit).ToArray());
string letters = new string(str.Where(char.IsLetter).ToArray());
int number;
if (!int.TryParse(digits, out number)) //int.Parse would do the job since only digits are selected
{
Console.WriteLine("Something weired happened");
}
string newStr = letters + (++number).ToString("D5");
output would be:
newStr = "MD00495"
Assuming that you only need to increment the numeric portion of the string, and that the structure of the strings is always - bunch of non-numeric characters followed by a bunch of numerals, you can use a regular expression to break up the string into these two components, convert the numeric portion to an integer, increment and then concatenate back.
var match = Regex.Match("MD123", #"^([^0-9]+)([0-9]+)$");
var num = int.Parse(match.Groups[2].Value);
var after = match.Groups[1].Value + (num + 1);
You need to find the position of the first digit in the string.
Then split the string into 2 fields.
0 1 2 3 4 5 6
M D 0 0 4 9 4
The first field will be the non numeric part "MD"
The second field will be the numeric part "00494"
Increment the numeric only part to "00495"
You will lose the leading zero's so you'll need to pad your new number with the same amount of zero's once you've incremented.
Then join the 2 fields.
The accepted answer does not work if there is a number in the middle of the string e.g. XXX123YYY456, exceptions are thrown.
I have written a generic method that will increment the end of the string and you can pass it the minimum amount of digits.
public static string IncrementStringEnd(string name, int minNumericalCharacters = 1)
{
var prefix = System.Text.RegularExpressions.Regex.Match(name, #"\d+$");
if (prefix.Success)
{
var capture = prefix.Captures[0];
int number = int.Parse(capture.Value) + 1;
name = name.Remove(capture.Index, capture.Length) + number.ToString("D" + minNumericalCharacters);
}
return name;
}
Test Results:
MD00494 : MD00495
XXX123YYY456 : XXX123YYY457
SD50MRF999 : SD50MRF1000
SD50MRF9 : SD50MRF010
For testing purposes https://dotnetfiddle.net/j1f6wh
You can use regex:
int kod = int.Parse(Regex.Replace(sdesptchNo, "[^0-9]", "")) + 1;
string zeroStr=Regex.Replace(sdesptchNo, "[^0-9]", "");
string newZeroStr="";
for (int x=0;x<zeroStr.length;x++)
if (zeroStr[x]=='0') newZeroStr=newZeroStr+"0";
else break;
string newVal=Regex.Replace(sdesptchNo, "[0-9]", "") + newZeroStr + kod;
UPDATED: This will save your zero
string sDispatchNo = "MS00914";
var pattern = #"^[a-zA-Z]+";
var strPart = Regex.Match(sDispatchNo, pattern).Value;
var noPart = Regex.Replace(sDispatchNo, pattern, "");
var no = int.Parse(noPart);
var length = noPart.Length;
length = (no + 1)/(Math.Pow(10,length)) == 1 ? length + 1 : length;
var output = strPart + (no + 1).ToString("D" + length);
Here's my solution:
string str = Console.ReadLine();
string digits = new string(str.Where(char.IsDigit).ToArray());
string letters = new string(str.Where(char.IsLetter).ToArray());
string newStr;
int number;
if (!int.TryParse(digits, out number))
{
Console.WriteLine("Something weird happened");
}
if (digits.StartsWith("0"))
{
newStr = letters + (++number).ToString("D5");
}
else
{
newStr = letters + (++number).ToString();
}
Try it!
I use this to Increment/Decrement Barcodes
/// <summary>
/// Gets the number portion of the string and adds 1 to it
/// </summary>
public static string IncrementNumbers(this string numString)
{
if (numString.IsEmpty())
return numString;
else if (!numString.Where(Char.IsDigit).Any())
return numString;
else
{
string prefix = Regex.Match(numString, "^\\D+").Value;
string number = Regex.Replace(numString, "^\\D+", "");
int i = int.Parse(number) + 1;
return prefix + i.ToString($"D{numString.Length - prefix.Length}");
}
}
/// <summary>
/// Gets the number portion of the string and subtracts 1 from it
/// </summary>
public static string DecrementNumbers(this string numString)
{
if (numString.IsEmpty())
return numString;
else if (!numString.Where(Char.IsDigit).Any())
return numString;
else
{
string prefix = Regex.Match(numString, "^\\D+").Value;
string number = Regex.Replace(numString, "^\\D+", "");
int i = int.Parse(number) - 1;
return prefix + i.ToString($"D{numString.Length - prefix.Length}");
}
}
/// <summary>
/// Shortented IsNullOrWhiteSpace
/// </summary>
public static bool IsEmpty(this string str)
{
if (str.TrimFix() == null)
return true;
return false;
}
/// <summary>
/// Trims the String and returns Null if it's empty space
/// </summary>
public static string TrimFix(this string rawString)
{
if (!string.IsNullOrWhiteSpace(rawString))
{
return rawString.Trim();
}
return null;
}

Categories