Daily Archives: May 14, 2021
C# || How To Convert Bytes To Kilobytes, Megabytes, Gigabytes, Terabytes Using C#
The following is a module with functions which demonstrates how to convert bytes to decimal formats like kilobytes, megabytes, gigabytes, terabytes, petabytes, exabytes, zettabytes, and yottabytes, as well as binary formats like kibibytes, mebibytes, gibibytes, tebibytes, pebibytes, exbibytes, zebibytes, and yobibytes using C#.
The function demonstrated on this page follows the IEC standard, which means:
• 1 kilobyte = 1000 bytes (Decimal)
• 1 kibibyte = 1024 bytes (Binary)
This function allows you to convert bytes to a measurement unit, a measurement unit to bytes, and allows to convert from one measurement unit to another measurement unit.
1. Convert Bytes To Measurement Unit
The example below demonstrates the use of ‘Utils.Bytes.FromTo‘ to convert bytes to a measurement unit.
The optional function parameter allows you to specify the decimal places.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
// Convert Bytes To Measurement Unit // Declare values to convert var values = new[] { 2287879, 536870912, 1073741824 }; // Convert values foreach (var value in values) { // Convert bytes to megabyte var mb = Utils.Bytes.FromTo(Utils.Bytes.Unit.Byte, value, Utils.Bytes.Unit.Megabyte); // Convert bytes to mebibyte var mib = Utils.Bytes.FromTo(Utils.Bytes.Unit.Byte, value, Utils.Bytes.Unit.Mebibyte); // Display the converted values Console.WriteLine($"Bytes: {value}, Megabyte: {mb}, Mebibyte: {mib}"); } // expected output: /* Bytes: 2287879, Megabyte: 2.287879, Mebibyte: 2.18189144134521484375 Bytes: 536870912, Megabyte: 536.870912, Mebibyte: 512 Bytes: 1073741824, Megabyte: 1073.741824, Mebibyte: 1024 */ |
2. Convert Measurement Unit To Bytes
The example below demonstrates the use of ‘Utils.Bytes.FromTo‘ to convert a measurement unit to bytes.
The optional function parameter allows you to specify the decimal places.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// Convert Measurement Unit To Bytes // Declare values to convert var values = new[] { 1, 0.5M, 10.75M }; // Convert values foreach (var value in values) { // Convert gibibyte to byte var bytes = Utils.Bytes.FromTo(Utils.Bytes.Unit.Gibibyte, value, Utils.Bytes.Unit.Byte); // Display the converted values Console.WriteLine($"Gibibyte: {value}, Bytes: {bytes}"); } // expected output: /* Gibibyte: 1, Bytes: 1073741824 Gibibyte: 0.5, Bytes: 536870912.0 Gibibyte: 10.75, Bytes: 11542724608.00 */ |
3. Convert Measurement Unit To Measurement Unit
The example below demonstrates the use of ‘Utils.Bytes.FromTo‘ to convert a measurement unit to another measurement unit.
The optional function parameter allows you to specify the decimal places.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// Convert Measurement Unit To Measurement Unit // Declare values to convert var values = new[] { 1991, 1987, 28.31M, 19.22M }; // Convert values foreach (var value in values) { // Convert value from one unit to another var size = Utils.Bytes.FromTo(Utils.Bytes.Unit.Gigabyte, value, Utils.Bytes.Unit.Terabyte); // Display the converted values Display($"Gigabyte: {value}, Terabyte: {size}"); } // expected output: /* Gigabyte: 1991, Terabyte: 1.991 Gigabyte: 1987, Terabyte: 1.987 Gigabyte: 28.31, Terabyte: 0.02831 Gigabyte: 19.22, Terabyte: 0.01922 */ |
4. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 14, 2021 // Taken From: http://programmingnotes.org/ // File: Utils.cs // Description: Handles general utility functions // ============================================================================ using System; using System.Collections.Generic; namespace Utils { public static class Bytes { public enum Unit { Byte, // Decimal Kilobyte, Megabyte, Gigabyte, Terabyte, Petabyte, Exabyte, Zettabyte, Yottabyte, // Binary Kibibyte, Mebibyte, Gibibyte, Tebibyte, Pebibyte, Exbibyte, Zebibyte, Yobibyte } /// <summary> /// Converts a measurement 'Unit' to another measurement 'Unit' /// </summary> /// <param name="unitFrom">The measurement unit converting from</param> /// <param name="sizeFrom">The size of the 'from' measurement unit</param> /// <param name="unitTo">The measurement unit to convert to</param> /// <param name="decimalPlaces">The decimal places to round to</param> /// <returns>The value converted to the specified measurement unit</returns> public static decimal FromTo(Unit unitFrom, decimal sizeFrom, Unit unitTo , int? decimalPlaces = null) { var result = sizeFrom; if (unitFrom != unitTo) { if (unitFrom == Unit.Byte) { result = ConvertTo(unitTo, sizeFrom, decimalPlaces); } else if (unitTo == Unit.Byte) { result = ConvertFrom(unitFrom, sizeFrom, decimalPlaces); } else { result = ConvertTo(unitTo, ConvertFrom(unitFrom, sizeFrom), decimalPlaces); } } return result; } private enum Conversion { From, To } // Converts bytes to a measurement unit private static decimal ConvertTo(Unit unit, decimal bytes , int? decimalPlaces = null) { return Convert(Conversion.To, bytes, unit, decimalPlaces); } // Converts a measurement unit to bytes private static decimal ConvertFrom(Unit unit, decimal bytes , int? decimalPlaces = null) { return Convert(Conversion.From, bytes, unit, decimalPlaces); } private static decimal Convert(Conversion operation, decimal bytes, Unit unit , int? decimalPlaces) { // Get the unit type definition var definition = GetDefinition(unit); if (definition == null) { throw new ArgumentException($"Unknown unit type: {unit}", nameof(unit)); } // Get the unit value var value = definition.Value; // Calculate the result var result = operation == Conversion.To ? bytes / value : bytes * value; if (decimalPlaces.HasValue) { result = Math.Round(result, decimalPlaces.Value, MidpointRounding.AwayFromZero); } return result; } public enum Prefix { Decimal, Binary } public class Definition { public Prefix Prefix { get; set; } public int OrderOfMagnitude { get; set; } public decimal Multiple { get { return Prefix == Prefix.Decimal ? 1000 : 1024; } } public decimal Value { get { return System.Convert.ToDecimal(Math.Pow((double)Multiple, OrderOfMagnitude)); } } } public static Definition GetDefinition(Unit unit) { var definitions = GetDefinitions(); return definitions.ContainsKey(unit) ? definitions[unit] : null; } public static Dictionary<Unit, Definition> GetDefinitions() { if (definitions == null) { definitions = new Dictionary<Unit, Definition>(); // Place units in order of magnitude // Decimal units var decimals = new[] { Unit.Kilobyte, Unit.Megabyte, Unit.Gigabyte, Unit.Terabyte, Unit.Petabyte, Unit.Exabyte, Unit.Zettabyte, Unit.Yottabyte }; // Binary units var binary = new[] { Unit.Kibibyte, Unit.Mebibyte, Unit.Gibibyte, Unit.Tebibyte, Unit.Pebibyte, Unit.Exbibyte, Unit.Zebibyte, Unit.Yobibyte }; AddDefinitions(definitions, Prefix.Decimal, decimals); AddDefinitions(definitions, Prefix.Binary, binary); } return definitions; } private static Dictionary<Unit, Definition> definitions = null; private static void AddDefinitions(Dictionary<Unit, Definition> definitions , Prefix prefix, IEnumerable<Unit> units) { int index = 1; foreach (var unit in units) { if (!definitions.ContainsKey(unit)) { definitions.Add(unit, new Definition() { Prefix = prefix, OrderOfMagnitude = index }); } ++index; } } } }// http://programmingnotes.org/ |
5. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 14, 2021 // Taken From: http://programmingnotes.org/ // File: Program.cs // Description: The following demonstrates the use of the Utils Namespace // ============================================================================ using System; using System.Diagnostics; public class Program { static void Main(string[] args) { try { // Declare values to convert var values = new[] { 2287879, 536870912, 1073741824 }; // Convert values foreach (var value in values) { // Convert bytes to megabyte var mb = Utils.Bytes.FromTo(Utils.Bytes.Unit.Byte, value, Utils.Bytes.Unit.Megabyte); // Convert bytes to mebibyte var mib = Utils.Bytes.FromTo(Utils.Bytes.Unit.Byte, value, Utils.Bytes.Unit.Mebibyte); // Display the converted values Display($"Bytes: {value}, Megabyte: {mb}, Mebibyte: {mib}"); } Display(""); // Declare values to convert var values2 = new[] { 1, 0.5M, 10.75M }; // Convert values foreach (var value in values2) { // Convert gibibyte to byte var bytes = Utils.Bytes.FromTo(Utils.Bytes.Unit.Gibibyte, value, Utils.Bytes.Unit.Byte); // Display the converted values Display($"Gibibyte: {value}, Bytes: {bytes}"); } Display(""); // Declare values to convert var values3 = new[] { 1991, 1987, 28.31M, 19.22M }; // Convert values foreach (var value in values3) { // Convert value from one unit to another var size = Utils.Bytes.FromTo(Utils.Bytes.Unit.Gigabyte, value, Utils.Bytes.Unit.Terabyte); // Display the converted values Display($"Gigabyte: {value}, Terabyte: {size}"); } } catch (Exception ex) { Display(ex.ToString()); } finally { Console.ReadLine(); } } static void Display(string message) { Console.WriteLine(message); Debug.Print(message); } }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
C# || How To Parse A Delimited CSV File Using C#
The following is a module with functions which demonstrates how to parse a delimited CSV file using VB.NET.
This function parses a CSV file and returns its results as a List. Each List index represents a line in the CSV file, with each item in the list representing a record contained on that line.
The function demonstrated on this page uses FileIO.TextFieldParser to parse values in a CSV file.
Note: To use the function in this module, make sure you have a reference to ‘Microsoft.VisualBasic‘ in your project.
One way to do this is, in your Solution Explorer (where all the files are shown with your project), right click the ‘References‘ folder, click ‘Add Reference‘, then type ‘Microsoft.VisualBasic‘ in the search box, and add the reference titled Microsoft.VisualBasic in the results Tab.
1. Parse CSV File
The example below demonstrates the use of ‘Utils.Methods.ParseCsv‘ to parse a CSV file and return its results as a List.
The optional function parameter allows you to specify the delimiters. Default delimiter is a comma (,).
Sample CSV used in this example is the following:
1 2 3 4 5 6 |
Kenneth,Perkins,120 jefferson st.,Riverside, NJ, 08075 Jack,McGinnis,220 hobo Av.,Phila, PA,09119 "Jennifer ""Da Man""",Repici,120 Jefferson St.,Riverside, NJ,08075 Stephen,Tyler,"7452 Terrace ""At the Plaza"" road",SomeTown,SD, 91234 ,Blankman,,SomeTown, SD, 00298 "Joan ""the bone"", Anne",Jet,"9th, at Terrace plc",Desert City,CO,00123 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
// Parse CSV File // Read file into byte array byte[] fileBytes; // Parse the contents of the file into a list var fileContents = Utils.Methods.ParseCsv(fileBytes); // Display the contents of the file for (var lineIndex = 0; lineIndex < fileContents.Count; ++lineIndex) { var line = fileContents[lineIndex]; Console.WriteLine($"Line #{lineIndex + 1}"); foreach (var item in line) { Console.WriteLine($" Item: {item}"); } } // expected output: /* Line #1 Item: Kenneth Item: Perkins Item: 120 jefferson st. Item: Riverside Item: NJ Item: 08075 Line #2 Item: Jack Item: McGinnis Item: 220 hobo Av. Item: Phila Item: PA Item: 09119 Line #3 Item: Jennifer "Da Man" Item: Repici Item: 120 Jefferson St. Item: Riverside Item: NJ Item: 08075 Line #4 Item: Stephen Item: Tyler Item: 7452 Terrace "At the Plaza" road Item: SomeTown Item: SD Item: 91234 Line #5 Item: Item: Blankman Item: Item: SomeTown Item: SD Item: 00298 Line #6 Item: Joan "the bone", Anne Item: Jet Item: 9th, at Terrace plc Item: Desert City Item: CO Item: 00123 */ |
2. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 14, 2021 // Taken From: http://programmingnotes.org/ // File: Utils.cs // Description: Handles general utility functions // ============================================================================ using System; using System.Linq; using System.Collections.Generic; namespace Utils { public static class Methods { /// <summary> /// Parses a Csv file and returns its results as a List. /// Each List index represents a line in the Csv file, with each /// item in the list representing a record contained on that line. /// </summary> /// <param name="fileBytes">The Csv file as a byte array</param> /// <param name="delimiters">The Csv data delimiter</param> /// <returns>The the file contents as a List</returns> public static List<List<string>> ParseCsv(byte[] fileBytes , string delimiters = ",") { var results = new List<List<string>>(); using (var stream = new System.IO.MemoryStream(fileBytes)) { using (var parser = new Microsoft.VisualBasic.FileIO.TextFieldParser(stream)) { parser.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited; parser.Delimiters = delimiters.Select(letter => letter.ToString()).ToArray(); parser.HasFieldsEnclosedInQuotes = true; // Parse each line in the file while (!parser.EndOfData) { var currentLine = parser.ReadFields(); results.Add(currentLine.ToList()); } } } return results; } } }// http://programmingnotes.org/ |
3. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 14, 2021 // Taken From: http://programmingnotes.org/ // File: Program.cs // Description: The following demonstrates the use of the Utils Namespace // ============================================================================ using System; using System.Diagnostics; using System.Collections.Generic; public class Program { static void Main(string[] args) { try { // Read file into byte array byte[] fileBytes; // Parse the contents of the file into a list var fileContents = Utils.Methods.ParseCsv(fileBytes); // Display the contents of the file for (var lineIndex = 0; lineIndex < fileContents.Count; ++lineIndex) { var line = fileContents[lineIndex]; Display($"Line #{lineIndex + 1}"); foreach (var item in line) { Display($" Item: {item}"); } } } catch (Exception ex) { Display(ex.ToString()); } finally { Console.ReadLine(); } } static void Display(string message) { Console.WriteLine(message); Debug.Print(message); } }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
C# || How To Round A Number To The Nearest X Using C#
The following is a module with functions which demonstrates how to round a number to the nearest X using C#.
This function has the ability to either round a number to the nearest amount, always round up, or always round down. For example, when dealing with money, this is good for rounding a dollar amount to the nearest 5 cents.
1. Round – Nearest
The example below demonstrates the use of ‘Utils.Round.Amount‘ to round a number to the nearest 5 cents.
The optional function parameter determines they type of rounding to perform.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// Round - Nearest // Declare values to round var values = new decimal[] { 19.28M, 31.22M, 19.91M, 19.87M, 0.05M }; // Declare step amount var stepAmount = 0.05M; // Round to nearest amount foreach (var value in values) { Console.WriteLine($"Value: {value}, Rounded: {Utils.Round.Amount(value, stepAmount)}"); } // expected output: /* Value: 19.28, Rounded: 19.3 Value: 31.22, Rounded: 31.2 Value: 19.91, Rounded: 19.9 Value: 19.87, Rounded: 19.85 Value: 0.05, Rounded: 0.05 */ |
2. Round – Up
The example below demonstrates the use of ‘Utils.Round.Amount‘ to always round a number up to the nearest 5 cents.
The optional function parameter determines they type of rounding to perform.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// Round - Up // Declare values to round var values = new decimal[] { 19.28M, 31.22M, 19.91M, 19.87M, 0.05M }; // Declare step amount var stepAmount = 0.05M; // Round up to nearest amount foreach (var value in values) { Console.WriteLine($"Value: {value}, Rounded: {Utils.Round.Amount(value, stepAmount, Utils.Round.Type.Up)}"); } // expected output: /* Value: 19.28, Rounded: 19.3 Value: 31.22, Rounded: 31.25 Value: 19.91, Rounded: 19.95 Value: 19.87, Rounded: 19.9 Value: 0.05, Rounded: 0.05 */ |
3. Round – Down
The example below demonstrates the use of ‘Utils.Round.Amount‘ to always round a number down to the nearest 5 cents.
The optional function parameter determines they type of rounding to perform.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// Round - Down // Declare values to round var values = new decimal[] { 19.28M, 31.22M, 19.91M, 19.87M, 0.05M }; // Declare step amount var stepAmount = 0.05M; // Round down to nearest amount foreach (var value in values) { Console.WriteLine($"Value: {value}, Rounded: {Utils.Round.Amount(value, stepAmount, Utils.Round.Type.Down)}"); } // expected output: /* Value: 19.28, Rounded: 19.25 Value: 31.22, Rounded: 31.2 Value: 19.91, Rounded: 19.9 Value: 19.87, Rounded: 19.85 Value: 0.05, Rounded: 0.05 */ |
4. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 14, 2021 // Taken From: http://programmingnotes.org/ // File: Utils.cs // Description: Handles general utility functions // ============================================================================ using System; namespace Utils { public static class Round { public enum Type { Nearest, Up, Down } /// <summary> /// Rounds a number to the nearest X /// </summary> /// <param name="value">The value to round</param> /// <param name="stepAmount">The amount to round the value by</param> /// <param name="type">The type of rounding to perform</param> /// <returns>The value rounded by the step amount and type</returns> public static decimal Amount(decimal value, decimal stepAmount , Round.Type type = Round.Type.Nearest) { var inverse = 1 / stepAmount; var dividend = value * inverse; switch (type) { case Round.Type.Nearest: dividend = Math.Round(dividend); break; case Round.Type.Up: dividend = Math.Ceiling(dividend); break; case Round.Type.Down: dividend = Math.Floor(dividend); break; default: throw new ArgumentException($"Unknown type: {type}", nameof(type)); } var result = dividend / inverse; return result; } } }// http://programmingnotes.org/ |
5. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 14, 2021 // Taken From: http://programmingnotes.org/ // File: Program.cs // Description: The following demonstrates the use of the Utils Namespace // ============================================================================ using System; using System.Diagnostics; public class Program { static void Main(string[] args) { try { // Declare values to round var values = new decimal[] { 19.28M, 31.22M, 19.91M, 19.87M, 0.05M }; // Declare step amount var stepAmount = 0.05M; // Round to nearest amount foreach (var value in values) { Display($"Value: {value}, Rounded: {Utils.Round.Amount(value, stepAmount)}"); } Display(""); // Round up to nearest amount foreach (var value in values) { Display($"Value: {value}, Rounded: {Utils.Round.Amount(value, stepAmount, Utils.Round.Type.Up)}"); } Display(""); // Round down to nearest amount foreach (var value in values) { Display($"Value: {value}, Rounded: {Utils.Round.Amount(value, stepAmount, Utils.Round.Type.Down)}"); } } catch (Exception ex) { Display(ex.ToString()); } finally { Console.ReadLine(); } } static void Display(string message) { Console.WriteLine(message); Debug.Print(message); } }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
C# || How To Replace A Letter With Its Alphabet Position Using C#
The following is a module with functions which demonstrates how to replace a letter with its alphabet position using C#.
1. Replace With Alphabet Position
The example below demonstrates the use of ‘Utils.Methods.GetAlphabetPosition‘ to replace a letter with its alphabet position.
1 2 3 4 5 6 7 8 9 10 11 12 |
// Replace With Alphabet Position // Get alphabet position var result = Utils.Methods.GetAlphabetPosition("The sunset sets at twelve o' clock."); // Display the results Console.WriteLine(string.Join(" ", result)); // expected output: /* 20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11 */ |
2. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 14, 2021 // Taken From: http://programmingnotes.org/ // File: Utils.cs // Description: Handles general utility functions // ============================================================================ using System; using System.Collections.Generic; namespace Utils { public static class Methods { /// <summary> /// Gets the alphabet position of each character in a string /// </summary> /// <param name="text">The text to get the position</param> /// <returns>The alphabet position of each character</returns> public static List<int> GetAlphabetPosition(string text) { var alphabet = "abcdefghijklmnopqrstuvwxyz"; var result = new List<int>(); foreach (var letter in text.ToLower()) { var index = alphabet.IndexOf(letter); if (index > -1) { result.Add(index + 1); } } return result; } } }// http://programmingnotes.org/ |
3. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 14, 2021 // Taken From: http://programmingnotes.org/ // File: Program.cs // Description: The following demonstrates the use of the Utils Namespace // ============================================================================ using System; using System.Diagnostics; using System.Collections.Generic; public class Program { static void Main(string[] args) { try { var result = Utils.Methods.GetAlphabetPosition("The sunset sets at twelve o' clock."); Display(string.Join(" ", result)); } catch (Exception ex) { Display(ex.ToString()); } finally { Console.ReadLine(); } } static void Display(string message) { Console.WriteLine(message); Debug.Print(message); } }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
C# || How To Generate A Random String Of A Specified Length Using C#
The following is a module with functions which demonstrates how to generate a random code of a specified length using C#.
The function demonstrated on this page has the ability to generate random strings that contains only letters, only numerical digits, or alphanumeric strings.
1. Random Code – Alphabetical
The example below demonstrates the use of ‘Utils.Code.GetRandom‘ to generate a code of a specified length that contains only letters.
The optional function parameter determines the type of code that is generated.
1 2 3 4 5 6 7 8 9 10 11 12 |
// Random Code - Alphabetical // Generate code containing only letters var letters = Utils.Code.GetRandom(5); // Display the code Console.WriteLine($"Code: {letters}"); // example output: /* Code: PBduQ */ |
2. Random Code – Numeric
The example below demonstrates the use of ‘Utils.Code.GetRandom‘ to generate a code of a specified length that contains only digits.
The optional function parameter determines the type of code that is generated.
1 2 3 4 5 6 7 8 9 10 11 12 |
// Random Code - Numeric // Generate code containing only digits var numeric = Utils.Code.GetRandom(7, Utils.Code.Type.Numeric); // Display the code Console.WriteLine($"Code: {numeric}"); // example output: /* Code: 1768033 */ |
3. Random Code – Alphanumeric
The example below demonstrates the use of ‘Utils.Code.GetRandom‘ to generate a code of a specified length that is alphanumeric.
The optional function parameter determines the type of code that is generated.
1 2 3 4 5 6 7 8 9 10 11 12 |
// Random Code - Alphanumeric // Generate alphanumeric code var alphaNumeric = Utils.Code.GetRandom(10, Utils.Code.Type.AlphaNumeric); // Display the code Console.WriteLine($"Code: {alphaNumeric}"); // example output: /* Code: iSL3bwu09O */ |
4. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 14, 2021 // Taken From: http://programmingnotes.org/ // File: Utils.cs // Description: Handles general utility functions // ============================================================================ using System; namespace Utils { public static class Code { public enum Type { /// <summary> /// Code contains only letters /// </summary> Alphabetical, /// <summary> /// Code contains only digits /// </summary> Numeric, /// <summary> /// Code contains letters and digits /// </summary> AlphaNumeric } /// <summary> /// Generates a random string of a specified length according to the type /// </summary> /// <param name="length">The length of the random string</param> /// <param name="type">The type of string to generate</param> /// <returns>The random string according to the type</returns> public static string GetRandom(int length , Code.Type type = Code.Type.Alphabetical) { var digits = "0123456789"; var alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; var source = string.Empty; switch (type) { case Code.Type.Alphabetical: source = alphabet; break; case Code.Type.Numeric: source = digits; break; case Code.Type.AlphaNumeric: source = alphabet + digits; break; default: throw new ArgumentException($"Unknown type: {type}", nameof(type)); } var r = new Random(); var result = new System.Text.StringBuilder(); while (result.Length < length) { result.Append(source[r.Next(0, source.Length)]); } return result.ToString(); } } }// http://programmingnotes.org/ |
5. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 14, 2021 // Taken From: http://programmingnotes.org/ // File: Program.cs // Description: The following demonstrates the use of the Utils Namespace // ============================================================================ using System; using System.Diagnostics; public class Program { static void Main(string[] args) { try { // Generate code containing only letters var letters = Utils.Code.GetRandom(5); // Display the code Display($"Code: {letters}"); Display(""); // Generate code containing only digits var numeric = Utils.Code.GetRandom(7, Utils.Code.Type.Numeric); // Display the code Display($"Code: {numeric}"); Display(""); // Generate alphanumeric code var alphaNumeric = Utils.Code.GetRandom(10, Utils.Code.Type.AlphaNumeric); // Display the code Display($"Code: {alphaNumeric}"); } catch (Exception ex) { Display(ex.ToString()); } finally { Console.ReadLine(); } } static void Display(string message) { Console.WriteLine(message); Debug.Print(message); } }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.