Is there a way to print array name [duplicate] - c#

This question already has answers here:
How do you get a variable's name as it was physically typed in its declaration? [duplicate]
(11 answers)
Closed 7 years ago.
I have an array
int[] arr1 = new int[] { 1, 2, 3 };
Console.WriteLine("How to print the text arr1 ?? ");
I need the array name i.e. 'arr1' in console output/Writeline, seems simple but need help.
Edit :
Output should be
arr1
NOT
1 2 3
Good to know, this is achieved in PHP too.

If you declare/initialize variables in a far more complicated way you could...
echo "<pre>";
$var_name="Foo"; // naming the var "Foo"
$$var_name="Bar"; // declaring the var "Foo"
echo "value: ". $Foo . "<br><br>";
foreach(compact($var_name) as $key=>$value){ // refering to var name
echo "name: " . $key . "<br><br>";
}
echo "pair: ";
print_r(compact($var_name));
echo "<pre>" ;
But we'd still need to get it through compact($var_name) instead of compact($Foo)

Related

Increment MAC Address By 1 [duplicate]

This question already has answers here:
how to Convert string MAC Address to Hex [closed]
(2 answers)
Hex increment / loop till FFF
(1 answer)
Convert int to hex and then into a format of 00 00 00 00
(3 answers)
Closed 2 years ago.
I have a seemingly simple request that I have no idea how to do in C#. I have searched and only found answers using other languages.
I have a string that includes a MAC address. For example, string sMyMACAddress = "00:1D:FE:12:37:1A";
How do I take this MAC address, increment it by 1, and pop out the resultant new next-in-sequence MAC Address in a new string such as sMyNextMACAddress?
Can someone help me with this or at least point me in the right direction?
I've tried the following after the latest suggestions. UPDATE: I've provided the answer below as my question was closed prior to an answer being accepted.
string sMACAddressIn = "00:1D:FE:12:37:1A";
string sMACAddressOut = "";
Console.WriteLine("MAC Address going in: " + sMACAddressIn);
sMACAddressIn = sMACAddressIn.Replace(":", ""); // Format this otherwise you get an incorrect format error on numberstyles.hexnumber
long iLastMACAddressHex = long.Parse(sMACAddressIn, NumberStyles.HexNumber);
iLastMACAddressHex++;
sMACAddressOut = string.Join(":", BitConverter.GetBytes(iLastMACAddressHex).Reverse() .Select(b => b.ToString("X2"))).Substring(6);
Console.WriteLine("MAC Address going out: " + sMACAddressOut);
Console.Read();
I get the following result.
MAC Address going in: 00:1D:FE:12:37:1A
MAC Address going out: 00:1D:FE:12:37:1B

Convert Python to C# [duplicate]

This question already has answers here:
Understanding slicing
(38 answers)
Closed 4 years ago.
Hi I'm trying to convert som Python code to C# I'm struck understanding this line of code
n = int(e[2:10], 16)
e is a string looking like this:
0100000180a6fa85de8dd3381cc277b046d7e3856307519d03da4e3ff5dca52de833c56951ab3e539a161df98454be311fd242407b25bf7b8e84c322f06f913d712393922bd1477d2cf3a9d2ba14bb00f8b2d7a203376afed0e1782e49ea55d43cee8e3bb8331f3f8aa81955bae8fcd118f640b4cd49d787bd8a12d57f424b371d07f08de67ab8f40bf5894288920adfe9480cfbec7deef073c3f137d71dff9d4ab967d9178648961cd2def00d376cf01dca6a4c6428243cef23eeab9791f5cd7d66f5293879b7ed83abf600f78426491c57c8a61e
n = int(e[2:10], 16) takes characters 2..10 from e and interprets them as hexadecimal characters to interpret as an integer.
That is, for your input,
>>> e = '0100000180a6fa85de8dd3...'
>>> f = e[2:10]
>>> f
'00000180'
>>> int(f, 16)
384
so you should be able to do the same with something like Convert.ToInt32(e.Substring(2, 8), 16) in C#.
At first, you're using string slicing (from 2nd to 9th character) using [2:10]. Then you're converting them to (decimal) int from hexadecimal.
Which will result n = 384.

c# deleting the 0s of an int, but not if it is 20 [duplicate]

This question already has answers here:
How to remove leading zeros using C#
(9 answers)
Closed 5 years ago.
In my string start can be all sorts of numbers (1 until 99), but when the numbers get generated, 1 always get shown like 01. Is there an way to remove that 0, without if the number is 20 that the number get changed to 2?
You can use the String.TrimStart method:
string num = "0001";
num = num.TrimStart('0');
Another solution:
if (start.ElementAt(0) == '0')
start = start.Remove(0, 1);
or shorter:
start = start.ElementAt(0) == '0' ? start.Substring(1) : start;

Transforming a string using Regex C# [duplicate]

This question already has answers here:
C# convert int to string with padding zeros?
(15 answers)
Closed 8 years ago.
i've been kicking my self for a while now with regex, and unable to find a proper solution. I've been trying to transform a string using Regex.Replace() method in C# which should prepend 0 to existing string if length is less than 5, the conversion might be as follow
Input String ----------- Output String
12345 ----------- 12345
123 ----------- 00123
123456 ----------- 123456
any help will be appreciated
You can use String.PadLeft: "1234".PadLeft(5, '0')
It can be like
var outputString = Regex.Replace(inputString, #"\d+", n => n.Value.PadLeft(5, '0'));
but you don't really need regex in this case.
You don't need any regex
if(str.Length < 5){
for(var i = 0; i < 5 - str.length; i++)
str = "0" + str;
}
The above is all you need. What you're doing is if the input string's Length is less than 5, you're just subtracting and looping, adding them.

Convert a string to multidimensional array

I have a matrix, which is read from the console. The elements are separated by spaces and new lines. How can I convert it into a multidimensional int array in c#? I have tried:
String[][] matrix = (Console.ReadLine()).Split( '\n' ).Select( t => t.Split( ' ' ) ).ToArray();
but when I click enter, the program ends and it doesn't allow me to enter more lines.
The example is:
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
5 6 7 8 9
int[,] Matrix = new int[n_rows,n_columns];
for(int i=0;i<n_rows;i++){
String input=Console.ReadLine();
String[] inputs=input.Split(' ');
for(int j=0;j<n_columns;j++){
Matrix[i,j]=Convert.ToInt32(inputs[j]);
}
}
you can try this to load the matrix
First things first, Console.ReadLine() reads a single line from the input. So in order to accept multiple lines you need to do 2 things:
Have a loop which allows the user to continue entering lines of data. You could let them go until they leave a line blank, or you could fix it to 5 lines of input
Store these "lines" of data for future processing.
Assuming the user can enter any number of lines, and a blank line (just hitting enter) indicates the end of data entry something like this will suffice
List<string> inputs = new List<string>();
var endInput = false;
while(!endInput)
{
var currentInput = Console.ReadLine();
if(String.IsNullOrWhitespace(currentInput))
{
endInput = true;
}
else
{
inputs.Add(currentInput);
}
}
// when code continues here you have all the user's input in separate entries in "inputs"
Now for turning that into an array of arrays:
var result = inputs.Select(i => i.Split(' ').ToArray()).ToArray();
That will give you an array of arrays of strings (which is what your example had). If you wanted these to be integers you could parse them as you go:
var result = inputs.Select(i => i.Split(' ').Select(v => int.Parse(v)).ToArray()).ToArray();
// incoming single-string matrix:
String input = #"1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
5 6 7 8 9";
// processing:
String[][] result = input
// Divide in to rows by \n or \r (but remove empty entries)
.Split(new[]{ '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries)
// no divide each row into columns based on spaces
.Select(x => x.Split(new[]{ ' ' }, StringSplitOptions.RemoveEmptyEntries))
// case from IEnumerable<String[]> to String[][]
.ToArray();
result:
String[][] result = new string[]{
new string[]{ "1","2","3","4","5" },
new string[]{ "2","3","4","5","6" },
new string[]{ "3","4","5","6","7" },
new string[]{ "4","5","6","7","8" },
new string[]{ "5","6","7","8","9" }
};
It can be done in multiple ways
You can read a single line containing multiple numbers separated by a char, split by that char obtaining an array of ints and then you should fetch a matrix.
With out-of-the-box linq there is no trivial way for the fetching step and i think it is not really the case to use third-party libraries from codeplex like LinqLib or something.

Categories

Resources