Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I wanted to design a vb.net program which finds the longest word from a string. With the help of other users i managed to do that and i added other string operations. Overall the program now counts the number of symbols, has word count, interval count, finds longest and shortest word and the average word size. I thought the code could help others who have the same issues with those operations like me so i posted it below.
Here is a image of the program: https://i.stack.imgur.com/KcPNa.png
This is how the final code looks:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim a As String = TextBox1.Text
Dim a1 As Integer = Len(a) ' string size
Dim a3 As String = a.Split(" ").Length - 1 ' interval count
Dim a4 As String = a.Split(" ").OrderByDescending(Function(j) j.Length).FirstOrDefault 'longest word
Dim a5 As String = a.Split(" ").OrderByDescending(Function(j) j.Length).LastOrDefault 'shortest word
Dim a6 As String = a.Split(" ").Average(Function(j) j.Length) 'average word count
TextBox2.Text = a1
TextBox4.Text = a3
TextBox3.Text = a3 + 1 'word count is just 1 more than interval count
TextBox5.Text = a4
TextBox6.Text = a5
TextBox7.Text = a6
End Sub
I can not provide an solution in vb but maybe my c# implementation will give you a hint.
string source = "some string";
string longest = string.empty;
foreach(string s in source.Split(' ')) {
if (s.Length > longest.Length) {
longest = s;
}
}
Console.WriteLine(longest);
Tip: Next Time it would be helpfull to ask more specific questions.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 months ago.
Improve this question
For an example if column value is "ABC 123 981" need to extract only 123... like so if its "456_wert" need to extract only 456 using access VBA code. Can somebody please help on this.
Parse First Consecutive Digits
Sub StrFirstDigitsTEST()
Const pString As String = "a123.456b"
Dim rString As String: rString = StrFirstDigits(pString)
Debug.Print rString, Len(rString)
' Result:
' 123 3
End Sub
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose: Returns a string's ('ParseString') first consecutive digits
' in a string.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function StrFirstDigits(ByVal ParseString As String) As String
Dim ResultString As String
Dim Char As String
Dim FoundDigit As Boolean
Dim n As Long
For n = 1 To Len(ParseString)
Char = Mid(ParseString, n, 1)
If Char Like "#" Then
If Not FoundDigit Then FoundDigit = True
ResultString = ResultString & Char
Else
If FoundDigit Then Exit For
End If
Next n
StrFirstDigits = ResultString
End Function
Parsing strings is fairly simple if data has a consistent structure. Does not seem to be the case here so gets complicated. Your second example could be accomplished with Val("456_wert") but because the first example does not follow same pattern, will require more complex code. Probably have to test each character until a number is encountered. Based on samples provided, something like:
Function GetNumber(varS As Variant) As Variant
Dim x As Integer
GetNumber = Null
If varS & "" Like "*#*" Then
For x = 1 To Len(varS)
If IsNumeric(Mid(varS, x, 1)) Then
GetNumber = Val(Mid(Replace(varS, " ", "|"), x))
Exit For
End If
Next
End If
End Function
Place the procedure in a general module and call it from query or textbox.
SELECT table.*, GetNumber([source field]) AS Nbr FROM table;
=GetNumber([sourcefield])
Shouldn't really be necessary to populate a field in table with this extract, however, the SQL would be:
UPDATE tablename SET fieldname = GetNumber([source field])
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have a text file that contains data as follows:
[Section A]
55555
66666
77777 (all on separate lines)
[Section B]
AAAAA
BBBBB (each on a separate line)
I just want to know how I can read this data in, and place the data in [Section A] only into listboxA and the data in [Section B] into listboxB.
This code depends on the pattern being exactly as depicted in your question. I placed the text file in the bin\Debug folder for testing but you will need the full path if located elsewhere.
The first Do loop looks for the empty line between Section A and Section B. The final Do loop stops when it reaches the end of the lines array.
Private Sub OpCode()
Dim lines = File.ReadAllLines("Sections.txt")
Dim index = 0
If lines(0) = "[Section A]" Then
index = 1
Do While lines(Index) <> ""
ListBox1.Items.Add(lines(index))
index += 1
Loop
End If
index += 1
If lines(index) = "[Section B]" Then
index += 1
Do Until index = lines.Length
ListBox2.Items.Add(lines(index))
index += 1
Loop
End If
End Sub
Regex
It can be an easy task through the Regex. Consider the following example:
Imports System.IO
Imports System.Text.RegularExpressions
'...
Private Sub TheCaller()
Dim path = "TheFullPathOfTheTextFile"
Dim patt = "(\[.*\]\s)([A-Za-z0-9\s\,.\-_!##$%^&*()=+;:'`~|""?<>\/\\]+)"
Dim matches = Regex.Matches(File.ReadAllText(path),
patt, RegexOptions.Multiline).Cast(Of Match)
If matches.Count = 2 Then
ListBoxA.Items.AddRange(
matches.First().Groups(2).Value.
Split({ControlChars.NewLine}, StringSplitOptions.RemoveEmptyEntries)
)
ListBoxB.Items.AddRange(
matches.Last().Groups(2).Value.
Split({ControlChars.NewLine}, StringSplitOptions.RemoveEmptyEntries)
)
End If
End Sub
Note that, Groups(1) of each match captures the [Section X] part where X either A or B in your example. The Groups(2) captures the data of the section as string. Split this string on vbCrLf which is ControlChars.NewLine to get strings arrays so you can insert them into your ListBoxes.
See the online Regex test here.
Extension Methods
Alternatively, you can relay on the extensions to get the data of both sections through the TakeWhile and SkipWhile methods:
Private Sub TheCaller()
ListBoxA.DataSource = Nothing
ListBoxB.DataSource = Nothing
Dim allLines = File.ReadAllLines(path)
ListBoxA.DataSource = allLines.Skip(1).
TakeWhile(Function(x) x <> "[Section B]").
Where(Function(x) Not String.IsNullOrWhiteSpace(x)).ToList
ListBoxB.DataSource = allLines.SkipWhile(Function(x) x <> "[Section B]").
Skip(1).Where(Function(x) Not String.IsNullOrWhiteSpace(x)).ToList
End Sub
Note: Binding the ListBoxes to data sources as an alternative of adding the items manually.
The Skip method in both queries is to skip the [Section x] line.
Loop
A simple For..Each loop without using any extensions:
Private Sub TheCaller()
Dim listBox = ListBoxA
For Each line In File.ReadAllLines(path)
If line = "[Section B]" Then
listBox = ListBoxB
Continue For
ElseIf line = "[Section A]" Then
Continue For
End If
If Not String.IsNullOrWhiteSpace(line) Then
listBox.Items.Add(line)
End If
Next
End Sub
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm trying the following code to find the location of several values:
Dim destino as String
Dim origen as String
destino="A"
origen="B"
Dim fila as Integer
fila = Application.WorksheetFunction.Match(1, (Range("F:F") = origen) * (Range("G:G") = destino), 0)
But it doesn't work. Does anybody know why?
Sub Tester()
Dim f As Integer
Dim destino as String
Dim origen as String
destino = "B"
origen = "R"
f = ActiveSheet.Evaluate("=MATCH(1,(C:C=""" & destino & """) * (D:D=""" & origen & """),0)")
Debug.Print f '>> 6
End Sub
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to convert this little code from Vba to Vb.net without success.
Would like some help please.
Dim str As String, i As Long
For i = 0 To lstPages.ListCount - 1
If lstPages.Selected(i) Then
If str <> vbNullString Then str = str & "-"
str = str & lstPages.List(i)
End If
Next
So you want the third column, from all selected rows of the ListView, in one string separated by "-"?
Yes that's right.
Then do:
Dim values As New List(Of String)
For Each lvi As ListViewItem In lstPages.SelectedItems
values.Add(lvi.SubItems(2).Text)
Next
Dim str As String = String.Join("-", values)
Debug.Print(str)
I think you could do something like this:
For i as integer = 0 To lstPages.ListCount - 1
If lstPages.Selected(i) Then
If Not String.IsNullOrEmpty(str) Then
str &= "-"
str &= lstPages.List(i)
End If
Next
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I have an array of 6 elements , and I want to fill 18 textboxes with those members randomly each time . I want only to repeat the item 2 times . I have this code :
FlatTextBox1.Text = (subjects.Item(Int(Rnd() * (subjects.Count - 1))))
FlatTextBox2.Text = (subjects.Item(Int(Rnd() * (subjects.Count - 1))))
.
.
.
.
.
.
That continues till the end . Now the problem is that some items get's repeated 3 times and others 1 time so there's no equality . How can I fix this problem ?
Assuming you made a typo and wanted the items repeated 3 times, instead of 2, since 3*6=18:
Public Class Form1
Private R As New Random
Private subjects() As String = {"cat", "dog", "fish", "hamster", "lizard", "bird"}
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim values As New List(Of String)
values.AddRange(subjects)
values.AddRange(subjects)
values.AddRange(subjects)
Dim index As Integer
Dim matches() As Control
For i As Integer = 1 To 18
index = R.Next(values.Count)
matches = Me.Controls.Find("FlatTextBox" & i, True)
matches(0).Text = values(index)
values.RemoveAt(index)
Next
End Sub
End Class