VB6 code explanation - vb.net

I need to convert some of the legacy code which is currently in VB6 into C#. I am not able to understand this piece of code. Especially the InStr function, could someone please help me out with this and suggest me it's C# equivalent.
For i = 1 To Len(sString)
sChar = Mid$(sString, i, 1)
iPos = InStr(1, "0123456789", sChar, vbBinaryCompare)
If iPos > 0 Then
sRetStr = sRetStr & sChar
End If
Next i

The InStr finds the (one-based) index of a string in another string. The closest equivalent in the modern .Net string methods is .IndexOf. However, I would replace the code you have with this C# statement.
string sRetStr = (sString.Where((c) => char.IsDigit(c)).ToArray()).ToString();

I'd pare that code down to this:
sRetStr = Regex.Replace(sSTring, "[^0-9]", "");

Related

VBA code lower case to upper case using Mid string

I've gotten stuck with this VBA code. Any help would be greatly appreciated. I'm trying to change the first letters of 2 words from lower case to upper case. Also, how should I take the space in between these two words into consideration in the code?
I haven't been able to execute the code as I keep getting this compile error: "Argument not optional".
Function Properword(Text)
Dim rText
rText = Len(rText)
If rText(Mid(1, 1)) = LCase(Str) Then
rText = UCase(Str)
If rText(Mid(6, 1)) = LCase(Str) Then
rText = UCase
End If
End Function
Cheers!
First of all, you don't have to use UDF. Simply use inbuilt WorksheetFunction.Proper function to achieve ProperCase.
If you still want to create UDF, an example would be
Function Properword(strTxt)
Dim arrTxt
arrTxt = Split(strTxt, " ")
For i = LBound(arrTxt) To UBound(arrTxt)
arrTxt(i) = UCase(Left(arrTxt(i), 1)) & Mid(arrTxt(i), 2)
Next
Properword = Join(arrTxt, " ")
End Function
Finally, issues with your code
rText = Len(rText) ~~ this means rText will contain a numeric value because Len returns the lenght of the string
If rText(Mid(1, 1)) = LCase(Str) Then ~~ Mid takes the string as first argument followed by start point and then end point (optional).
not sure what you were trying to do in the following lines.
rText = UCase(Str)
If rText(Mid(6, 1)) = LCase(Str) Then
rText = UCase
In addition to the Excel function PROPER
str = WorksheetFunction.Proper("UPPER lower") ' "Upper Lower"
There is also the VBA.StrConv function:
str = StrConv("UPPER lower", vbProperCase) ' "Upper Lower"
To convert only parts of the string to uppercase, you can use RegEx, or the Mid statement:
Mid(str, 1, 1) = UCase(Mid(str, 1, 1)) ' makes the first letter uppercase

Longest Common substring breaking issue

Hi I have a function that finds the longest common substring between two strings. It works great except it seems to break when it reaches any single quote mark: '
This causes it to not truly find the longest substring sometimes.
Could anyone help me adjust this function so it includes single quotes in the substring? I know it needs to be escaped someplace I'm just not sure where.
Example:
String 1: Hi there this is jeff's dog.
String 2: Hi there this is jeff's dog.
After running the function the longest common substring would be:
Hi there this is jeff
Edit: seems to also happen with "-" as well.
It will not count anything after the single quote as part of the substring.
Here's is the function:
Public Shared Function LongestCommonSubstring(str1 As String, str2 As String, ByRef subStr As String)
Try
subStr = String.Empty
If String.IsNullOrEmpty(str1) OrElse String.IsNullOrEmpty(str2) Then
Return 0
End If
Dim num As Integer(,) = New Integer(str1.Length - 1, str2.Length - 1) {}
Dim maxlen As Integer = 0
Dim lastSubsBegin As Integer = 0
Dim subStrBuilder As New StringBuilder()
For i As Integer = 0 To str1.Length - 1
For j As Integer = 0 To str2.Length - 1
If str1(i) <> str2(j) Then
num(i, j) = 0
Else
If (i = 0) OrElse (j = 0) Then
num(i, j) = 1
Else
num(i, j) = 1 + num(i - 1, j - 1)
End If
If num(i, j) > maxlen Then
maxlen = num(i, j)
Dim thisSubsBegin As Integer = i - num(i, j) + 1
If lastSubsBegin = thisSubsBegin Then
subStrBuilder.Append(str1(i))
Else
lastSubsBegin = thisSubsBegin
subStrBuilder.Length = 0
subStrBuilder.Append(str1.Substring(lastSubsBegin, (i + 1) - lastSubsBegin))
End If
End If
End If
Next
Next
subStr = subStrBuilder.ToString()
Return subStr
Catch e As Exception
Return ""
End Try
End Function
I tried it with dotnetfiddle and there it is working with your Code you posted. Please activate your warnings in your project. You have function with no return value and you return an integer or a string. This is not correct. How are you calling your function?
Here is my example I tested for you:
https://dotnetfiddle.net/mVBDQp
Your code works perfectly like Regex! As far as I can see, there is really nothing wrong with your code.
Here I even tested it under more severe case:
Public Sub Main()
Dim a As String = ""
Dim str1 As String = "Hi there this is jeff''s dog.-do you recognize this?? This__)=+ is m((a-#-&&*-ry$##! <>Hi:;? the[]{}re this|\ is jeff''s dog." 'Try to trick the logic!
Dim str2 As String = "Hi there this is jeff''s dog. ^^^^This__)=+ is m((a-#-&&*-ry$##! <>Hi:;? the[]{}re this|\ is jeff''s dog."
LongestCommonSubstring(str1, str2, a)
Console.WriteLine(a)
Console.ReadKey()
End Sub
Note that I put '-$#^_)=+&|\{}[]?!;:.<> all there. Plus I tried to trick your code by giving early result.
But the result is excellent!
You could probably put more actual samples on the inputs which give you problems. Else, you could possibly describe the environment that you use/deploy your code into. Maybe the problem lies elsewhere and not in the code.
The quickest way to solve this would be to use an escape code and replace all the ' with whatever escape code you use

Help Visual Basic mixing characters

I'm making an application that will change position of two characters in Word.
Imports System.IO
Module Module1
Sub Main()
Dim str As String = File.ReadAllText("File.txt")
Dim str2 As String() = Split(str, " ")
For i As Integer = 0 To str2.Length - 1
Dim arr As Char() = CType(str2(i), Char())
For ia As Integer = 0 To arr.Length() - 1 Step 2
Dim pa As String
pa = arr(ia + 1)
arr(ia + 1) = arr(ia)
arr(ia) = pa
Next ia
For ib As Integer = 0 To arr.Length - 1
Console.Write(arr(ib))
File.WriteAllText("File2.txt", arr(ib))
Next ib
File.WriteAllText("File2.txt", " ")
Console.Write(" ")
Next i
Console.Read()
End Sub
End Module
For example:
Input: ab
Output: ba
Input: asdasd asdasd
Output: saadds saadds
Program works good, it is mixing characters good, but it doesn't write text to the file. It will write text in console, but not in file.
Note: Program is working only with words that are divisible by 2, but it's not a problem.
Also, it does not return any error message.
Your code is overwriting the file that you have already written with a single space (" ") each time round.
You should only open the file once, and append to it using a stream writer:
Using output = File.CreateText("file2.txt")
' Put the for loop here.
End Using
There are some other things wrong with your code. Firstly, use For Each instead of For, this makes your code much more simple and readable. Secondly, try to avoid For loops altogether where possible. For instance, instead of iterating over the characters to output them one at a time, just create a new string from the char array, and write that:
Dim shuffledWord As New String(arr)
output.Write(shuffledWord)
Some of your types are plain wrong, i.e. you are using String in places instead of Char. You should always use Option Strict On. Then the compiler will not tolerate such code.
You should also prefer to use framework methods over VB-specific methods. This makes it easier to understand for C# programmers, and also makes it easier to translate and change (that is, use the Split method of strings instead of a free function, use ToCharArray instead of a cast to Char() …).
Finally, use meaningful variable names. str, str2 and arr are particularly cryptic because they don’t tell the reader of the code anything of interest about the variables.
Sub Main()
Dim text As String = File.ReadAllText("File.txt")
Dim words As String() = str.Split(" "c)
Using output = File.CreateText("file2.txt")
For Each word In words
dim wordChars = word.ToCharArray()
For i As Integer = 0 To wordChars.Length - 1 Step 2
Dim tmp As Char = wordChars(i + 1)
wordChars(i + 1) = wordChars(i)
arr(i) = tmp
Next
Dim shuffledWord As New String(wordChars)
output.Write(shuffledWord + " ")
Console.Write(huffledWord + " ")
Next
End Using
Console.Read()
End Sub

is there a group_concat function in ms-access?

is there a group_concat function in ms-access or something similar?
You should ask yourself if you need a generic solution (another is by Allen Browne) or if you need it just for the present purpose. If you really only need it this once, do it the easy way.
On a side note, when concatenating lists in VBA code, take advantage of a trick taught to me by long-time Access guru Trevor Best, and that's to stick the delimiter at the beginning of every value and then use Mid() to strip it off. Instead of this inside your loop through the child records:
If Len(strOutput) = 0 Then
strOutput = NewValue
Else
strOutput = strOutput & ", " & NewValue
End If
...use this inside the loop:
strOutput = strOutput & ", " & NewValue
...and then when you exit the loop, strip off the leading delimiter:
strOutput = Mid(strOutput, 3)
This has implications all over the place and simplifies code for concatenation in a whole host of contexts.
There's an access function to group multiple values into one value (a custom aggregate, I guess.) The link is http://www.rogersaccesslibrary.com/Otherdownload.asp?SampleName='Generic%20Function%20To%20Concatenate%20Child%20Records'
but the site is down for now. If you google the href, you'll find lots of referneces and examples.
I found this post by Duane Hookum (a Microsoft MVP) that claims to be able to do what you want. I have not tested it though.
By the way, in case you are interested, this is how I found it:
First search: group_concat access lead me to this post with this answer but the link was broken.
Then I searched again after the content that the answer was attempting to link to, and found it: site:http://www.rogersaccesslibrary.com/ concatenate.
No. Access does not have a GROUP_CONCAT function. However, it is possible to create a VBA function which will let you pass a string containing a SQL statement and get the equivalent functionality (not that I'd recommend it but it is possible).
Taking my own personal wayback machine, here is some code I wrote back when dinosaurs ruled the Earth:
Public Function ListQuery(SQL As String _
, Optional ColumnDelimiter As String = " " _
, Optional RowDelimter As String = vbCrLf) As String
'PURPOSE: to return a combined string from the passed query
'ARGS:
' 1. SQL is a valid Select statement
' 2. ColumnDelimiter is the character(s) that separate each column
' 3. RowDelimiter is the character(s) that separate each row
'RETURN VAL:
'DESIGN NOTES:
Const PROCNAME = "ListQuery"
Const MAXROWS = 100
Const MAXCOLS = 10
Dim oConn As ADODB.Connection
Dim oRS As ADODB.Recordset
Dim oField As ADODB.Field
Dim sRow As cString
Dim sResult As cString
On Error GoTo ProcErr
Set sResult = New cString
Set sRow = New cString
Set oConn = GetADOConn()
sResult.Clear
Do Until oRS.EOF
sRow.Clear
For Each oField In oRS.Fields
With sRow
If .Length > 0 Then
.Append ColumnDelimiter
End If
.Append Nz(oField.Value)
End With
Next oField
sRow.Trim
If sRow.Length > 0 Then
With sResult
.Append sRow
.Append RowDelimter
End With
End If
oRS.MoveNext
Loop
oRS.Close
oConn.Close
With sResult
If .Right(Len(RowDelimter)).Value = RowDelimter Then
.Length = .Length - Len(RowDelimter)
End If
End With
FunctionResult:
ListQuery = sResult.Value
CleanUp:
Set sResult = Nothing
Set sRow = Nothing
Set oField = Nothing
Set oRS = Nothing
Set oConn = Nothing
Exit Function
ProcErr:
' logging code...
Resume CleanUp
End Function
The GetADOConn function is a centralized function to retrieve the current database connection. cString is a class that mimics the behavior of .NET's StringBuilder class but was written long before .NET was anything other than a TLD and marketing hype. Since this is getting called on every row, VBA's built-in string concatenation will be slow and thus something like a StringBuilder class is needed. The original code (which I've partially modified) had a cap on the number of rows and columns that could be used which is what the constants are all about.

How can I get the nickname and message from raw IRC data in vb.net

Well basically I've got a vb.net script connecting to IRC, and I'm working on making it a basic chat system, but I've run into a problem.
Say I receive this:
:nickname!name#tw-32151D9B.hsd1.vt.comcast.net PRIVMSG #channel :message
I want to grab specific information to output to the user.
I want to grab nickname and message
How can I go about doing this?
I thought about using regex, but I can't figure out how to make regex grab message since there's nothing after it.
I love IRC. The following code will do what you want assuming your raw data is in the variable strData.
Dim strNickName As String = String.Empty
Dim strMessage As String = String.Empty
Dim intToMessage As Integer = 0
Dim intParse As Integer = 0
intParse = InStr(strData, "!")
strNickName = Mid(strData, 2, (intStart - 2))
intToMessage = InStr(strData, "PRIVMSG #")
intParse = InStr(Mid(strData, intToMessage, (Len(strData) - intToMessage)), ":")
strMessage = Mid(strData, (intToMessage + intStart), (Len(strData) - (intToMessage + intStart - 1)))
You can use RegEx to get everything between the first : and !
(?<=:).*?(?=!)
and then look for everything between the last #channel : and the end of the line
(?<=#channel :).*?(?=$)
This is simple but should take into account that someone may use a semi-colon (:) in the message.