how to check what the first character of a string is in vb - vb.net

I have the following code, which reads the date and time from some DateTimePickers in VB.
I need to be able to determine if the first value is a 0 or a 1, (eg 09:12... or 12:13...) and if it starts with a 0 to remove that character from the string.
this is what i have so far, but it takes the first character regardless.
DateFrom = Form1.DateTimePickerFrom.Value.ToString
DateTo = Form1.DateTimePickerTo.Value.ToString
VarTimeFrom = Form1.HourTimePickerFrom.Value.ToString
VarTimeTo = Form1.HourTimePickerTo.Value.ToString
Dim DateFromManipulated = Left(DateFrom, 10)
Dim DateToManipulated = Left(DateTo, 10)
Dim TimeFromManipulated = Right(VarTimeFrom, 9)
Dim TimeToManipulated = Right(VarTimeTo, 9)
If Left(DateFromManipulated, 1) = 0 Then
TimeFromMan = TimeFromManipulated.Remove(0, 1)
Else
TimeFromMan = TimeFromManipulated
End If
If Left(TimeFromManipulated, 1) = 0 Then
TimeToMan = TimeToManipulated.Remove(0, 1)
Else
TimeToMan = TimeToManipulated
End If
Console.WriteLine(DateFromManipulated)
Console.WriteLine(TimeToMan)
Console.WriteLine(TimeFromManipulated)
Console.WriteLine(TimeFromMan)
Console.WriteLine(DateToManipulated)
Console.WriteLine(TimeToManipulated)
I get the following:
09/11/2012
1:36:00
06:36:00
6:36:00
08/01/2013
11:36:00
Thanks in advance!
Mike

A string in VB.NET won't compare as equal to an integer. You could just reference character zero, though:
If DateFromManipulated(0) = "0"c Then DateFromManipulated = DateFromManipulated.Substring(1)
... however, you should be just formatting your date the way you want it to begin with:
Dim dateFrom As String = DateTimePickerFrom.Value.ToString("M/dd/yyyy H:mm:ss")
... for example. (M doesn't have a leading zero, as opposed to MM; same with H.) You can find all the format strings here: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

Related

Ascending Order Textbox Separated with Comma

I'm new here. I have a textbox,
Textbox1.text = 1,2,7,4,11.
I want to be Output:
1,2,4,7,11.
Textbox1.text = 1,2,7,4,11.
I want to be Output:
1,2,4,7,11.
VB.Net
I found this code and it works for who wants it.
Code:
Private Sub Array()
Dim InputNumbers, SplitInputNumbers, ArrayCount, ReSort, iterInputNum, Num1, Num2
InputNumbers = OutputText1.Text
SplitInputNumbers = Split(InputNumbers, ",")
ArrayCount = UBound(SplitInputNumbers)
ReSort = "YES"
While ReSort = "YES"
ReSort = "NO"
For iterInputNum = 0 To ArrayCount
If iterInputNum < ArrayCount Then
If CInt(SplitInputNumbers(iterInputNum)) > CInt(SplitInputNumbers(iterInputNum + 1)) Then
Num1 = SplitInputNumbers(iterInputNum)
Num2 = SplitInputNumbers(iterInputNum + 1)
SplitInputNumbers(iterInputNum + 1) = Num1
SplitInputNumbers(iterInputNum) = Num2
ReSort = "YES"
End If
End If
Next
End While
Dim iterSortedNum, SortedNumericArray
For iterSortedNum = 0 To ArrayCount
If iterSortedNum = 0 Then
SortedNumericArray = SplitInputNumbers(iterSortedNum)
Else
SortedNumericArray = SortedNumericArray & "," & SplitInputNumbers(iterSortedNum)
End If
Next
OutputText1.Text = (SortedNumericArray)
You could do something like this. It takes your string splits it into an array. Converts each substring into a number, Making a new Integer array. Sorts that new array. and then using join converts it back into a comma separated string
Dim str = "1,2,7,4,11"
Dim b = String.Join(",", str.Split(",").Select(Function(x) Integer.Parse(x.Trim())).OrderBy(Function(x) x))

How to compare Strings for Percentage Match using vb.net?

I am banging my head against the wall for a while now trying different techniques.
None of them are working well.
I have two strings.
I need to compare them and get an exact percentage of match,
ie. "four score and seven years ago" TO "for scor and sevn yeres ago"
Well, I first started by comparing every word to every word, tracking every hit, and percentage = count \ numOfWords. Nope, didn't take into account misspelled words.
("four" <> "for" even though it is close)
Then I started by trying to compare every char in each char, incrementing the string char if not a match (to count for misspellings). But, I would get false hits because the first string could have every char in the second but not in the exact order of the second. ("stuff avail" <> "stu vail" (but it would come back as such, low percentage, but a hit. 9 \ 11 = 81%))
SO, I then tried comparing PAIRS of chars in each string. If string1[i] = string2[k] AND string1[i+1] = string2[k+1], increment the count, and increment the "k" when it doesn't match (to track mispellings. "for" and "four" should come back with a 75% hit.) That doesn't seem to work either. It is getting closer, but even with an exact match it is only returns 94%. And then it really gets screwed up when something is really misspelled. (Code at the bottom)
Any ideas or directions to go?
Code
count = 0
j = 0
k = 0
While j < strTempName.Length - 2 And k < strTempFile.Length - 2
' To ignore non letters or digits '
If Not strTempName(j).IsLetter(strTempName(j)) Then
j += 1
End If
' To ignore non letters or digits '
If Not strTempFile(k).IsLetter(strTempFile(k)) Then
k += 1
End If
' compare pair of chars '
While (strTempName(j) <> strTempFile(k) And _
strTempName(j + 1) <> strTempFile(k + 1) And _
k < strTempFile.Length - 2)
k += 1
End While
count += 1
j += 1
k += 1
End While
perc = count / (strTempName.Length - 1)
Edit: I have been doing some research and I think I initially found the code from here and translated it to vbnet years ago. It uses the Levenshtein string matching algorithm.
Here is the code I use for that, hope it helps:
Sub Main()
Dim string1 As String = "four score and seven years ago"
Dim string2 As String = "for scor and sevn yeres ago"
Dim similarity As Single =
GetSimilarity(string1, string2)
' RESULT : 0.8
End Sub
Public Function GetSimilarity(string1 As String, string2 As String) As Single
Dim dis As Single = ComputeDistance(string1, string2)
Dim maxLen As Single = string1.Length
If maxLen < string2.Length Then
maxLen = string2.Length
End If
If maxLen = 0.0F Then
Return 1.0F
Else
Return 1.0F - dis / maxLen
End If
End Function
Private Function ComputeDistance(s As String, t As String) As Integer
Dim n As Integer = s.Length
Dim m As Integer = t.Length
Dim distance As Integer(,) = New Integer(n, m) {}
' matrix
Dim cost As Integer = 0
If n = 0 Then
Return m
End If
If m = 0 Then
Return n
End If
'init1
Dim i As Integer = 0
While i <= n
distance(i, 0) = System.Math.Max(System.Threading.Interlocked.Increment(i), i - 1)
End While
Dim j As Integer = 0
While j <= m
distance(0, j) = System.Math.Max(System.Threading.Interlocked.Increment(j), j - 1)
End While
'find min distance
For i = 1 To n
For j = 1 To m
cost = (If(t.Substring(j - 1, 1) = s.Substring(i - 1, 1), 0, 1))
distance(i, j) = Math.Min(distance(i - 1, j) + 1, Math.Min(distance(i, j - 1) + 1, distance(i - 1, j - 1) + cost))
Next
Next
Return distance(n, m)
End Function
Did not work for me unless one (or both) of following are done:
1) use option compare statement "Option Compare Text" before any Import declarations and before Class definition (i.e. the very, very first line)
2) convert both strings to lowercase using .tolower
Xavier's code must be correct to:
While i <= n
distance(i, 0) = System.Math.Min(System.Threading.Interlocked.Increment(i), i - 1)
End While
Dim j As Integer = 0
While j <= m
distance(0, j) = System.Math.Min(System.Threading.Interlocked.Increment(j), j - 1)
End While

'Char' is not a member of 'String'" in VB.NET

Scenario is described below:
In txtDiscountRate.Text it has a value which is "0.996010500406591".
In my coding I did this:
txtDiscountRate.Text = Math.Round(Val(txtDiscountRate.Text.Trim), 6) 'means considering round till 6th digit
It is giving the value 0.99601 because of 6th digit after decimal is 0. But I want to put a condition in the decimal value.
So if on 6th digit after decimal is ( 0 or 1 or 2 or 3 or 4 ) and 7th digit after decimal is available, then it will round until 7th position.
Or else it will round until 6th position.
I got a solution (shown in the code below) from this site for this problem. I tried to implement but the below code throws an error:
CInt(Str(1).Char(5)) is showing error this error -> " 'Char' is not a member of 'String'".
This is my whole code so far:
Dim str() As String = Split(CStr(Dec), ".")
If CInt(Str(1).**Char(5)**) < 5 Then 'It's Char number 5 since it's a zero-based index. So the first number = Index 0.
txtDiscountRate.Text = Math.Round(Val(txtDiscountRate.Text.Trim), 7)
Else
txtDiscountRate.Text = Math.Round(Val(txtDiscountRate.Text.Trim), 6)
End If
Correct solution is needed.
I think that following function will help you and it is your solution.
Function GetDecimalValue(ByVal value As String) As Decimal
Dim valueFromDot As String = value.Substring(IIf(value.IndexOf(".") < 0, 0, value.IndexOf(".") + 1))
If (valueFromDot.Length > 5) Then
If (CInt(valueFromDot(5).ToString()) < 5 And CInt(valueFromDot(6).ToString()) > 0) Then
GetDecimalValue = Math.Round(CDec(value), 7)
Else
GetDecimalValue = Math.Round(CDec(value), 6)
End If
Else
GetDecimalValue = CDec(value)
End If
End Function

vb.net convert number to alphanumeric equivalent

I need to convert a four digit number to a three digit alphanumeric number where
001-999 = 001-999
1000 = 00A
1027 = 01A
etc.. up to whatever = ZZZ
I am very new to programming and cannot figure out how to proceed with this issue. Any help would be GREATLY appreciated.
How does this work for you?
Private Function ConvertMyNumber(toConvert As UShort) As String
Const MaxValueToConvert = 3885S
If (toConvert > MaxValueToConvert) Then Throw New ArgumentException(String.Format("Argument value of {0} exceeds maximum possible value of {1}.", toConvert, MaxValueToConvert))
Const NumeringSchemeThreshold = 1000
Const TotalResultLength = 3
Const PaddingChar = "0"c
If (toConvert < NumeringSchemeThreshold) Then Return toConvert.ToString().PadLeft(TotalResultLength, PaddingChar)
Dim adjustedValue = (toConvert - NumeringSchemeThreshold) 'since we're starting with this numbering scheme at NumeringSchemeThreshold
Const NumbersInAlphabet = 26
Dim moddedValue = (adjustedValue Mod NumbersInAlphabet) '0 to NumbersInAlphabet - 1 based on the cycle
Dim numCycles = Fix(adjustedValue / NumbersInAlphabet) 'What "cycle number" it is, i.e. the number of times around the alphabet loop.
Dim suffix As String = String.Empty
Dim prefix As String = CStr(numCycles)
Const firstStepThreshold = 100
Const secondStepThreshold = 110
Const LastAlphabetChar = "Z"c
If (numCycles >= firstStepThreshold And numCycles < secondStepThreshold) Then
numCycles = numCycles - firstStepThreshold
prefix = CStr(numCycles)
suffix = LastAlphabetChar
ElseIf (numCycles >= secondStepThreshold) Then
numCycles = numCycles - secondStepThreshold
suffix = LastAlphabetChar & LastAlphabetChar
prefix = String.Empty
End If
Const AsciiCharValueOffset = 65
'concat the cycle number to the converted modded letter, and return the zero-padded result.
Return (prefix & CChar(Char.ConvertFromUtf32(moddedValue + AsciiCharValueOffset)) & suffix).PadLeft(TotalResultLength, PaddingChar)
End Function

128 bit hex keygen

So my professor gave me a challenge to build a decoder that could break his special formula. It was described to be 32 characters in length, alphanumeric numeric when entered but then "it has a system... the first 106 bits must be 50% 1's and the rest 0's, the remaining 22 bits are basically a hash of the previous bits so that the key can be checked..." were his exact words. Sounds to me like a 128 bit encryption with a twist. I found the below but I need VB2010 or VS2010, this says php.
<?php
function string_random($characters, $length)
{
$string = '';
for ($max = mb_strlen($characters) - 1, $i = 0; $i < $length; ++ $i)
{
$string .= mb_substr($characters, mt_rand(0, $max), 1);
}
return $string;
}
// 128 bits is 16 bytes; 2 hex digits to represent each byte
$random_128_bit_hex = string_random('0123456789abcdef', 32);
// $random_128_bit_hex might be: '4374e7bb02ae5d5bc6d0d85af78aa2ce'
Would that work? Or does it need converting? Please help. Oh and thank you :)
I wasn't promised extra credit but either way I would like to surprise him.
So the first 106 bit are 26 character and the first half of the 27.
You have first of all encode somehow the number of 0 and 1, while building the string you need to keep an eye to the number. An idea would be to build a map like this:
0 = 0000 = -4
1 = 0001 = -2
2 = 0010 = -2
3 = 0011 = 0
4 = -2
5 = 0
6 = 0
7 = +2
8 = -2
9 = 0
a = 0
b = +2
c = 0
d = +2
e = +2
f = +4
then everytime you extract a new random number you check the number associated to it and add it to a variable
balanceOfOneAndZero
your objective is have balanceOfOneAndZero = 0 when you hit your 27th character.
to do that you need a control function, that takes current balanceOfOneAndZero, the proposed character proposedChar, and current string lenght currLenght.
Would be better to split the problem into two part. First is reaching the 26th character of the sequence with balanceOfOneAndZero between -2 and 2. Any other value is not acceptable, because your 27th character can have maximum two 1 or two 0 to completely balance the first 106 characters.
so your function should do something like (I'll write in sort of pseudo code since I don't have an IDE right now)
function checkNextLetter(Dim balanceOfOneAndZero As Integer, Dim proposedChar As Char,
Dim currentLenght as Integer) As Boolean
If( ((26 - currentLenght - 1) * 4 + 2) < MOD(Map.ValueOf(proposedChar) + balanceOfOneAndZero) ) Then
Return true
Else
Return false
ENd If
End function
This function basically check if accepting the new character will still make possible to Balance the number of 0 and 1 before the 26th character.
So your main function should have a loop every time it propose a new character, something like
proposedChar = new RandomChar
While (Not checkNextLetter(balanceOfOneAndZero, proposedChar, len(currentString))
proposedChar = new RandomChar
End While
currentString = currentString & proposedChar
this only until you hit the 26th character.
Than you have to check balanceOfOneAndZero, if its 2 you add a character that begin with 00, if it's 0 you can either have 10 or 01, if it's -2 you have to add a character that begin with 11.
After this I can't help you about the rest 22 character, since there are not enough information. You could brute force the rest
EDIT:
so to brute force the rest (il start from when you reach the 26th character):
Dim stringa1, stringa2, stringa3, stringa4 As String
If balanceOfOneAndZero = 2 Then
stringa1 = currentString & '0'
stringa2 = currentString & '1'
stringa3 = currentString & '2'
stringa4 = currentString & '3'
ELse If balanceOfOneAndZero = 0 Then
stringa1 = currentString & '4'
stringa2 = currentString & '5'
stringa3 = currentString & '6'
stringa4 = currentString & '7'
Else
stringa1 = currentString & 'c'
stringa2 = currentString & 'd'
stringa3 = currentString & 'e'
stringa4 = currentString & 'f'
End if
Function GenerateAllCombination(ByVal iLenght As Integer)
Dim arrayLista As New List(Of String)()
Dim arraySubLista As New List(Of String)()
If (iLenght > 1) Then
arraySubLista = GenerateAllCombination(iLenght -1)
for each objString As String in arraySubLista
for each ele As String in arrayValori
arrayLista.add(objString & ele)
loop
loop
Else
for each ele As String in arrayValori
arrayLista.add(ele)
loop
End If
End Function
Now if you use generateAllCombination you will have a List of string with ALL the combination of 5 character.
Now you just create 4 list by concatenating those combination with your string1 to string4 (string1 & combination) etc..
put all those result on a List of string, and you have 100% that at least ONE of the string will break your teacher code
I forgot, arrayValori must be a List with all values from "0" to "f"