I just start to learn c++/cli, please help.
How do i convert string '----' to string like 'A-C-' if only the 0 and second character in the string meet the condition.
char str[] = "-----";
if // 0 true
{str[0] = "A";}
if // 1 true
{str[1] = "B";}
if // 2 true
{str[2] = "C";}
if // 3 true
{str[3] = "D";}
Using the .Net StringBuilder class you can replace a char in a string at a give index :
StringBuilder ^sb = gcnew StringBuilder(myString);
sb[index] = myChar;
myString = sb->ToString();
Related
I have this conversion in my Kotlin class for Android:
val binary = "01000100000111001011011011100010111000110011010111010110"
val hexadecimal = BigInteger(binary, 2).toString(16)
Which is producing the expected value of 441CB6E2E335D6.
Now I want to reproduce this in Visual Basic and I am doing something like this:
Dim binary = "01000100000111001011011011100010111000110011010111010110"
Dim hexadecimal = BigInteger.Parse(binary, 2).ToString("X")
Which is producing 0A7108304A751AFEC876F740BC1F2CB59772FB7C6C753E.
I am not an expert in Visual Basic, but from what I researched, I think this is the right way to convert a binary to hexadecimal. What I am doing wrong?
You can write a simple parser for the string representing the bits:
Dim sb As StringBuilder = New StringBuilder()
For pos As Integer = 0 To binary.Length - 8 Step 8
sb.Append(Convert.ToByte(binary.Substring(pos, 8), 2).ToString("X2"))
Next
Console.WriteLine(sb) will print "441CB6E2E335D6"
Or use a Module to add an extension method to the string data type:
Imports System.Runtime.CompilerServices
Imports System.Text
Module modStringExtensions
<Extension()>
Public Function ToHexFromBits(ByVal Value As String) As String
If (Not (Value.Length Mod 8 = 0)) Then Throw New FormatException("Invalid string length")
Dim sb As StringBuilder = New StringBuilder()
For pos As Integer = 0 To Value.Length - 8 Step 8
sb.Append(Convert.ToByte(Value.Substring(pos, 8), 2).ToString("X2"))
Next
Return sb.ToString()
End Function
End Module
Then use the extension to convert the bits string to a HEX representation:
Dim result As String = binary.ToHexFromBits()
Following code is c#, but might not be too hard to translate it to vb.net.
string BinToHex(string value)
{
var res = new char[(int)(value.Length / 4)];
int j = res.Length-1;
for (int i = value.Length - 1; i > 0; i -= 4)
{
int x = ((int)value[i]-48)
+((int)value[i-1]-48)*2
+((int)value[i-2]-48)*4
+((int)value[i-3]-48)*8;
res[j--] = x.ToString("X")[0];
}
return new string(res);
}
Beware: it won't handle input that has not the proper number of bits (multiple of 4). Anyway, the idea is that you can translate between base 2 and base 16 without the use of base 10. You could even step from left to right.
I have a string looking like this:
a:391:i:0;s:12:"jnKKPkvpNnfn";i:1;s:12:"ic9VAk3PvQ3j";i:2;s:12:"PEBFuE6bGepr";i:3;s:12:"bwuxRkH6QbGp";i:4;s:12:"LSRDQbAKXc9q";i:5;s:12:"eLuVbSAxQCgo";}
And I want to get the text inside the quotations and send them to a listbox.
I know sort of how to do it, but in an ineffective way that might now work... So I'm asking for advice with an example on how to do it.
Thanks
This should get you started; the method will run through an input string and return an array of strings that are contained within quotes.
string[] ParseQuotes(string input)
{
List<string> matches = new List<string>();
bool open = false;
int index = -1;
for (int i = 0; i < input.Length; i++)
{
if (input[i] == '"')
{
if (!open)
{
open = true;
index = i;
}
else
{
open = false;
string match = input.Substring(index + 1, index - i - 1);
matches.Add(match);
}
}
}
return matches.ToArray();
}
Converted to VB...
Private Function ParseQuotes(input As String) As String()
Dim matches As New List(Of String)()
Dim open As Boolean = False
Dim index As Integer = -1
For i As Integer = 0 To input.Length - 1
If input(i) = """"C Then
If Not open Then
open = True
index = i
Else
open = False
Dim match As String = input.Substring(index + 1, index - i - 1)
matches.Add(match)
End If
End If
Next
Return matches.ToArray()
End Function
In your main code:
cbYourcomboBox.Items.Clear()
cbYourcomboBox.Items.AddRange(GetList(str).ToArray)
and then the function itself:
Public Function GetList(ByVal str As String) As List(Of String)
Dim ar As String()
Dim ar2 As List(Of String) = New List(Of String)
ar = Split(str, Chr(34))
' making sure there is a matching closing quote with - (UBound(ar) And 1)
For a As Integer = 1 To UBound(ar) - (UBound(ar) And 1) Step 2
ar2.Add(ar(a))
Next a
Return ar2
End Function
I am a little stuck with a simple Question: how to generate a simple random Boolean?
If am correct, a Boolean 0 = false and 1 = true, but how to suse that?
Current code:
Dim RandGen As New Random
Dim RandBool As Boolean
RandBool = Boolean.Parse(RandGen.Next(0, 1).tostring)
Or just simply:
Random rng = new Random();
bool randomBool = rng.Next(0, 2) > 0;
Saves some processing power of parsing text, whereas a simple compare is enough.
Edit: Second parameter is exclusive, so should be .Next(0, 2).
Dim RandGen As New Random
Dim RandBool As Boolean
RandBool = RandGen.Next(0, 2).ToString
TextBox1.Text = RandBool
Maybe something like this?
string[] trueOrFalse = { "false", "true"};
bool RandBool = bool.Parse(trueOrFalse[RandGen.Next(0,2)]);
I need to generate random strings in vb.net, which must consist of (randomly chosen) letters A-Z (must be capitalized) and with random numbers interspersed. It needs to be able to generate them with a set length as well.
Thanks for the help, this is driving me crazy!
If you can convert this to VB.NET (which is trivial) I'd say you're good to go (if you can't, use this or any other tool for what's worth):
/// <summary>
/// The Typing monkey generates random strings - can't be static 'cause it's a monkey.
/// </summary>
/// <remarks>
/// If you try hard enough it will eventually type some Shakespeare.
/// </remarks>
class TypingMonkey
{
private const string legalCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
static Random random = new Random();
/// <summary>
/// The Typing Monkey Generates a random string with the given length.
/// </summary>
/// <param name="size">Size of the string</param>
/// <returns>Random string</returns>
public string TypeAway(int size)
{
StringBuilder builder = new StringBuilder();
char ch;
for (int i = 0; i < size; i++)
{
ch = legalCharacters[random.Next(0, legalCharacters.Length)];
builder.Append(ch);
}
return builder.ToString();
}
}
Then all you've got to do is:
TypingMonkey myMonkey = new TypingMonkey();
string randomStr = myMonkey.TypeAway(size);
Why don't you randomize a number 1 to 26 and get the relative letter.
Something like that:
Dim output As String = ""
Dim random As New Random()
For i As Integer = 0 To 9
output += ChrW(64 + random.[Next](1, 26))
Next
Edit: ChrW added.
Edit2: To have numbers as well
Dim output As String = ""
Dim random As New Random()
Dim val As Integer
For i As Integer = 0 To 9
val = random.[Next](1, 36)
output += ChrW(IIf(val <= 26, 64 + val, (val - 27) + 48))
Next
C#
public string RandomString(int length)
{
Random random = new Random();
char[] charOutput = new char[length];
for (int i = 0; i < length; i++)
{
int selector = random.Next(65, 101);
if (selector > 90)
{
selector -= 43;
}
charOutput[i] = Convert.ToChar(selector);
}
return new string(charOutput);
}
VB.Net
Public Function RandomString(ByVal length As Integer) As String
Dim random As New Random()
Dim charOutput As Char() = New Char(length - 1) {}
For i As Integer = 0 To length - 1
Dim selector As Integer = random.[Next](65, 101)
If selector > 90 Then
selector -= 43
End If
charOutput(i) = Convert.ToChar(selector)
Next
Return New String(charOutput)
End Function
How about:
Private Function GenerateString(len as integer) as String
Dim stringToReturn as String=""
While stringToReturn.Length<len
stringToReturn&= Guid.NewGuid.ToString().replace("-","")
End While
Return left(Guid.NewGuid.ToString(),len)
End Sub
Here's a utility class I've got to generate random passwords. It's similar to JohnIdol's Typing Monkey, but has a little more flexibility in case you want generated strings to contain uppercase, lowercase, numeric or special characters.
public static class RandomStringGenerator
{
private static bool m_UseSpecialChars = false;
#region Private Variables
private const int m_MinimumLength = 8;
private const string m_LowercaseChars = "abcdefghijklmnopqrstuvqxyz";
private const string m_UppercaseChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private const string m_NumericChars = "123456890";
private const string m_SpecialChars = "~?/##!£$%^&*+-_.=|";
#endregion
#region Public Methods
/// <summary>
/// Generates string of the minimum length
/// </summary>
public static string Generate()
{
return Generate(m_MinimumLength);
}
/// <summary>
/// Generates a string of the specified length
/// </summary>
/// <param name="length">The number of characters to generate</param>
public static string Generate(int length)
{
return Generate(length, Environment.TickCount);
}
#endregion
#region Private Methods
/// <summary>
/// Generates a string of the specified length using the specified seed
/// </summary>
private static string Generate(int length, int seed)
{
// Generated strings must contain at least 3 of the following character groups: uppercase letters, lowercase letters
// numerals, and special characters (!, #, $, £, etc)
// The generated string must be at least 4 characters so that we can add a single character from each group.
if (length < 4) throw new ArgumentException("String length must be at least 4 characters");
StringBuilder SB = new StringBuilder();
Random rand = new Random(seed);
// Ensure that we add all of the required groups first
SB.Append(GetRandomCharacter(m_LowercaseChars, rand));
SB.Append(GetRandomCharacter(m_UppercaseChars, rand));
SB.Append(GetRandomCharacter(m_NumericChars, rand));
if (m_UseSpecialChars)
SB.Append(GetRandomCharacter(m_SpecialChars, rand));
// Now add random characters up to the end of the string
while (SB.Length < length)
{
SB.Append(GetRandomCharacter(GetRandomString(rand), rand));
}
return SB.ToString();
}
private static string GetRandomString(Random rand)
{
int a = rand.Next(3);
switch (a)
{
case 1:
return m_UppercaseChars;
case 2:
return m_NumericChars;
case 3:
return (m_UseSpecialChars) ? m_SpecialChars : m_LowercaseChars;
default:
return m_LowercaseChars;
}
}
private static char GetRandomCharacter(string s, Random rand)
{
int x = rand.Next(s.Length);
string a = s.Substring(x, 1);
char b = Convert.ToChar(a);
return (b);
}
#endregion
}
To use it:
string a = RandomStringGenerator.Generate(); // Generate 8 character random string
string b = RandomStringGenerator.Generate(10); // Generate 10 character random string
This code is in C# but should be fairly easy to convert to VB.NET using a code converter.
Just be simple. for vb just do:
Public Function RandomString(size As Integer, Optional validchars As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz") As String
If size < 1 Or validchars.Length = 0 Then Return ""
RandomString = ""
Randomize()
For i = 1 To size
RandomString &= Mid(validchars, Int(Rnd() * validchars.Length) + 1, 1)
Next
End Function
This function allows for a base subset of chars to use or user can choose anything. For example you could send ABCDEF0123456789 and get random Hex. or "01" for binary.
Try this, it's the top answer already converted to VB!
Private Function randomStringGenerator(size As Integer)
Dim random As Random = New Random()
Dim builder As Text.StringBuilder = New Text.StringBuilder()
Dim ch As Char
Dim legalCharacters As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"
For cntr As Integer = 0 To size
ch = legalCharacters.Substring(random.Next(0, legalCharacters.Length), 1)
builder.Append(ch)
Next
Return builder.ToString()
End Function
Whats the best way to convert a list(of string) to a string with the values seperated by a comma (,)
String.Join(",", myListOfStrings.ToArray())
That depends on what you mean by "best". The least memory intensive is to first calculate the size of the final string, then create a StringBuilder with that capacity and add the strings to it.
The StringBuilder will create a string buffer with the correct size, and that buffer is what you get from the ToString method as a string. This means that there are no extra intermediate strings or arrays created.
// specify the separator
string separator = ", ";
// calculate the final length
int len = separator.Length * (list.Count - 1);
foreach (string s in list) len += s.Length;
// put the strings in a StringBuilder
StringBuilder builder = new StringBuilder(len);
builder.Append(list[0]);
for (int i = 1; i < list.Count; i++) {
builder.Append(separator).Append(list[i]);
}
// get the internal buffer as a string
string result = builder.ToString();
My solution:
string = ["a","2"]\n
newstring = ""
endOfString = len(string)-1
for item in string:
newstring = newstring + item
if item != string[endOfString]:
newstring = newstring ","'
A simple solution:
dim str as string = ""
for each item as string in lst
str += ("," & item)
next
return str.substring(1)
It takes off the first char from the string (",")