I need help with translating some code from VB to C#.
Public Function ToBase36(ByVal IBase36 As Double) As String
Dim Base36() As String = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}
Dim v As String
Dim i As Decimal
Do Until IBase36 < 1
i = IBase36 Mod 36
v = Base36(i) & v
IBase36 = Math.DivRem(Long.Parse(IBase36), 36, Nothing)
Loop
Return v
End Function
My problem is how type conversion works in VB, and this line gives me most trouble since IBase36 is a double, Math.DivRem() in this case should return long and Long.Parse() need string.
IBase36 = Math.DivRem(Long.Parse(IBase36), 36, Nothing)
Here is my translated, working code thanks to the JaredPar and others
public static string ToBase36(double IBase36)
{
string[] Base36 = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
string v = null;
long i = default(long);
while (!(IBase36 < 1))
{
IBase36 = Convert.ToDouble(Math.DivRem(Convert.ToInt64(IBase36), 36, out i));
v = Base36[i] + v;
}
return v;
}
To translate it's important to understand first how the VB.Net code functions. Under the hood it will essentially generate the following
Dim unused As Long
IBase36 = CDbl(Math.DivRem(Long.Parse(CStr(IBase36)), 36, unused)
Note: The unused variable is necessary because the third argument is an out. This is an important difference when translating to C#.
The most natural C# equivalent of the above is
long unused;
IBase36 = Convert.ToDouble(Math.DivRem(Long.Parse(IBase36.ToString()), 36, out unused);
Now try it:
long unused = null;
IBase36 = Convert.ToDouble(Math.DivRem(Convert.ToInt64(IBase36), 36, out unused));
IBase36 = (long)IBase36 / 36;
is what you want. Math.DivRem() returns the quotient which the above integer division should take care of. The third out parameter returns the remainder but since you don't care about it in vb. net code, you can just ignore that.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I have written this code to generate a random password. When I run it I get an error saying that public Main() method is supposed in public class.
using System;
namespace Rnadom_Password_generator
{
class Program
{
void Main()
{
string[] allCharacters = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "U", "V", "W", "Q", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "1", "2", "3", "4", "5", "6", "7", "7", "9", "0", "!", "#", "#", "$", "%", "^", "&", "*", "(", ")", "-", "=", "+", "*", "/"};
string password = "";
Random character = new Random();
int passwordLength = 10;
for (int i = 0; i < passwordLength; i++)
{
int rnadomNum = character.Next(0, allCharacters.Length);
password += allCharacters[rnadomNum];
Console.WriteLine(password);
}
}
}
}
What should I do?
Make sure your main method is static. Like this.
using System;
namespace Rnadom_Password_generator
{
class Program
{
static void Main(string[] args)
{
string[] allCharacters = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "U", "V", "W", "Q", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "1", "2", "3", "4", "5", "6", "7", "7", "9", "0", "!", "#", "#", "$", "%", "^", "&", "*", "(", ")", "-", "=", "+", "*", "/" };
string password = "";
Random character = new Random();
int passwordLength = 10;
for (int i = 0; i < passwordLength; i++)
{
int rnadomNum = character.Next(0, allCharacters.Length);
password += allCharacters[rnadomNum];
Console.WriteLine(password);
}
}
}
}
So basically, I have a list, and I have an empty string. My goal is to search if x has one of the values inside of it. Here is the code
string x = Console.ReadLine();
var strings = new List<string>() {"A", "B", "C", "D", "E", "F", "G", "H", "I","J", "K", "L", "M", "N", "O", "P", "Q","R", "S", "T", "U", "V", "W", "X", "Y","Z", "a", "b", "c", "d", "e", "f", "g", "h", "i","j", "k", "l", "m", "n", "o", "p", "q","r", "s", "t", "u", "v", "w", "x", "y","z"};
For example, if someone inputted "A B a 1" I want to see if there is a thing from the list in it (which there is) How would I do this? (C#)
I hope I understood you question. You can check if it exists using following.
var result = inputString.Split(new []{" "},StringSplitOptions.RemoveEmptyEntries)
.Any(x=>strings.Contains(x));
You need to split the input string based on whitespace, and compare if any of them exist in your original collection. You can do so using Linq
Forgive, new to c# always been a PHP man.
Have a form to generator random string for passwords based on the number of characters selected from drop down.
Having a problem with obtaining the values from drop down (casting the object to an int).
code:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string endword = "";
int chrnumber = Convert.ToInt16(comboBox1.SelectedValue);
string[] Nochars = { "q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "[", "]", "a", "s", "d", "f", "g", "h", "j", "k", "l", ";", "'", "#", "z", "x", "c", "v", "b", "n", "m", "/", "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "{", "}", "A", "S", "D", "F", "G", "H", "J", "K", "L", ":", "#", "~", "Z", "X", "C", "V", "B", "N", "M", "<", ">", "?", "!", "£", "$", "%", "^", "&", ".*", "(", ")", "_", "+", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "=" };
Random rndchar = new Random();
for (int i = 0; i < chrnumber; i++)
{
int iSelect = rndchar.Next(0, Nochars.Length);
string word1 = Nochars[iSelect];
string word2 = word1;
if (i == 0) { endword = word1; } else { endword += "." + word2; }
}
pwd.Text = endword;
}
//On form load
public Form1(){
List<Values> reasons = new List<Values> {
new Values("0", 0),
new Values("1", 1),
new Values("2", 2),
new Values("3", 3),
new Values("4", 4),
new Values("5", 5) };
comboBox1.DataSource = reasons;
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
reason = Convert.ToInt32(comboBox1.SelectedValue);
}
here the default value is 0, so your error will not occur at any point. I hope your combox datasource default value has ", which is causing this error.
or make sure the value part is not a alphabets/other characters instead of numbers in your datasource.
try this
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string endword = "";
int chrnumber = int.Parse(this.comboBox1.GetItemText(this.comboBox1.SelectedItem).ToString());// change line
string[] Nochars = { "q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "[", "]", "a", "s", "d", "f", "g", "h", "j", "k", "l", ";", "'", "#", "z", "x", "c", "v", "b", "n", "m", "/", "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "{", "}", "A", "S", "D", "F", "G", "H", "J", "K", "L", ":", "#", "~", "Z", "X", "C", "V", "B", "N", "M", "<", ">", "?", "!", "£", "$", "%", "^", "&", ".*", "(", ")", "_", "+", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "=" };
Random rndchar = new Random();
for (int i = 0; i < chrnumber; i++)
{
int iSelect = rndchar.Next(0, Nochars.Length);
string word1 = Nochars[iSelect];
string word2 = word1;
if (i == 0) {
endword = word1;
}
else {
endword += "." + word2;
}
}
pwd.Text = endword;
}
If I have input a string is it possible to check that the first letter does start with an input from a list of strings:
var dir = "FOLDERNAME";
var list = new List<string>() { "a", "b", "c", "d", "e", "f", "g", "s",
"t", "u", "v", "w", "z", "y", "z",
"1", "2", "3", "4", "5", "6", "7", "8", "9"};
if (!dir.ToLower().!StartsWith :MagicLinq: list) { Do Stuff; }
Or do I have to go the regex route?
One approach to consider:
var lower = new string(dir?.FirstOrDefault() ?? new char(), 1);
if (list.Contains(lower) {
The first line gets the first character from the string, and handles empty and null strings (by getting the null char), and then loads that char into a string.
You could simplify that if the List<string> was a List<char or HashSet<char> instead. Then you could remove the new string part.
You can check if the first letter is in the list:
if (list.Contains(""+dir[0])){}
If this check will be done many times using a HashSet<> would be more performant than a linear search on a List<>. Even if performance is not a concern a HashSet<> might better represent the data and how its used since each element is unique and ordering doesn't matter.
Here I'm using a HashSet<> of chars...
var dir = "FOLDERNAME";
var restrictedChars = new HashSet<char>(
new[] {
'A', 'B', 'C', 'D', 'E', 'F', 'G',
'S', 'T', 'U', 'V', 'W', 'Z', 'Y', 'Z',
'1', '2', '3', '4', '5', '6', '7', '8', '9'
}
);
if (!restrictedChars.Contains(dir[0]))
{
// Do stuff...
}
Note that I changed the restricted characters from lowercase to uppercase since char.ToUpper()/char.ToUpperInvariant() are the recommended way to normalize case for case-insensitive comparisons. You could then perform the check in a case-insensitive manner like this...
if (!restrictedChars.Contains(char.ToUpperInvariant(dir[0])))
{
// Do stuff...
}
Alternatively, you could use a HashSet<> of strings and pass in a case-insensitive StringComparer instance...
var dir = "FOLDERNAME";
var restrictedChars = new HashSet<string>(
new[] {
"a", "b", "c", "d", "e", "f", "g",
"s", "t", "u", "v", "w", "z", "y", "z",
"1", "2", "3", "4", "5", "6", "7", "8", "9"
},
StringComparer.OrdinalIgnoreCase
);
// Get a string from Substring() instead of dir[0].ToString()
if (!restrictedChars.Contains(dir.Substring(0, 1)))
{
// Do stuff...
}
With this approach the case of the restricted character strings fed into the HashSet<> doesn't matter.
This is how i'd do it
String dir = "FOLDERNAME";
var MyList = new List<string>() { "a", "b", "c", "d", "e", "f", "g", "s",
"t", "u", "v", "w", "z", "y", "z",
"1", "2", "3", "4", "5", "6", "7", "8", "9"};
Console.WriteLine((MyList.IndexOf(dir.Substring(0, 1).ToLower()) != -1) ? "True" : "False");
Console.ReadLine();
When I try to replace the the inputed morse code into text I get a problem. Basically the problem is that when the user inputs the ".", the prorgram prints the letter "E"(which is "." in morse code) and ignores all of the other periods after it to make other letters with two or more consecutive periods.
How should I solve this?
I know that this is probably a very newbie question but I've been struggling all day to find an answer for this.
Here's the code
public partial class Morsetext : PhoneApplicationPage
{
public string[] aakkoset = { ".", "A", "B", "C", "D", "E",
"F", "G", "H", "I", "J",
"K", "L", "M", "N", "O",
"P", "Q", "R", "S", "T",
"U", "V","W", "X", "Y",
"Z", "Ä", "Ö", "0", "1",
"2", "3", "4", "5", "6",
"7", "8", "9", "?", ":",
",", "#", "/", "=", " ",
};
public string[] morse = {".-.-.-", ".-", "-...", "-.-.", "-..", ".",
"..-.", "--.", ".... ", "..", ".---",
"-.-", ".-..", "--", "-.", "---",
".--.", "--.-", ".-.", "...", "-",
"..-", "...-", ".--", "-..-", "-.--",
"--..", ".-.-", "---.", "-----", ".----",
"..---", "...--", "....-", ".....", "-....",
"--...", "---..","----.", "..--..", "---...",
"-....-", ".--.-.", "-..-.", "-...-", " ",
};
public Morsetext()
{
InitializeComponent();
}
private void bShort_Click(object sender, RoutedEventArgs e)
{
char piste = '.';
tBoxMorse2.Text += piste.ToString();
}
private void tBoxMorse2_TextChanged(object sender, TextChangedEventArgs e)
{
tBlockText2.Text = tBoxMorse2.Text.ToUpper()
.Replace(morse[0],aakkoset[0])
.Replace(morse[1],aakkoset[1])
.Replace(morse[2],aakkoset[2])
.Replace(morse[3],aakkoset[3])
.Replace(morse[4],aakkoset[4])
.Replace(morse[5],aakkoset[5])
.Replace(morse[6],aakkoset[6])
.Replace(morse[7],aakkoset[7])
.Replace(morse[8],aakkoset[8])
.Replace(morse[9],aakkoset[9])
.Replace(morse[10],aakkoset[10])
.Replace(morse[11],aakkoset[11])
.Replace(morse[12],aakkoset[12])
.Replace(morse[13],aakkoset[13])
.Replace(morse[14],aakkoset[14])
.Replace(morse[15],aakkoset[15])
.Replace(morse[16],aakkoset[16])
.Replace(morse[17],aakkoset[17])
.Replace(morse[18],aakkoset[18])
.Replace(morse[19],aakkoset[19])
.Replace(morse[20],aakkoset[20])
.Replace(morse[21],aakkoset[21])
.Replace(morse[22],aakkoset[22])
.Replace(morse[23],aakkoset[23])
.Replace(morse[24],aakkoset[24])
.Replace(morse[25],aakkoset[25])
.Replace(morse[26],aakkoset[26])
.Replace(morse[27],aakkoset[27])
.Replace(morse[28],aakkoset[28])
.Replace(morse[29],aakkoset[29])
.Replace(morse[30],aakkoset[30])
.Replace(morse[31],aakkoset[31])
.Replace(morse[32],aakkoset[32])
.Replace(morse[33],aakkoset[33])
.Replace(morse[34],aakkoset[34])
.Replace(morse[35],aakkoset[35])
.Replace(morse[36],aakkoset[36])
.Replace(morse[37],aakkoset[37])
.Replace(morse[38],aakkoset[38])
.Replace(morse[39],aakkoset[39])
.Replace(morse[40],aakkoset[40])
.Replace(morse[41],aakkoset[41])
.Replace(morse[42],aakkoset[42])
.Replace(morse[43],aakkoset[43])
.Replace(morse[44],aakkoset[44]);
}
Morse code can be decoded using dichotomic search. The decision tree looks something like this
The simplest solution is to reorder your replaces from longest morse string first to shortest morse string last.