characters replace using vb.net 2012 - vb.net

i have a program that replace ing in some string and its return original verb in that srting like he was playing out door will be he was play out door ...etc
i just want the play without whole string
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myInput As String = TextBox1.Text
Dim myOutput As String = Replace(myInput, "ing", "")
Label1.Text = myOutput
End Sub

Private Function getVerbOfSetence(ByVal str As String) As String
Dim strSpl() As String = str.Split(" ")
For i = 0 To strSpl.Length - 1
If strSpl(i).ToLower.EndsWith("ing") Then
Return strSpl(i).ToLower.Replace("ing", "")
End If
Next
Return "noVerb"
End Function

The fastest way is to use a one-line Regex.
Dim Output As String = Regex.Match(myInput, "\p{L}+(?=ing[^\p{L}])", RegexOptions.IgnoreCase).Value
A Regex is a class capable of matching strings based on patterns. It's great to use and usually very fast. The pattern is the second string which I've passed to the Match() method. My pattern works like this:
The \p{L}+ part means that it should match every character that is a unicode letter. + means that it should match one or more letters.
The (?=ing[^\p{L}]) part means that the match must end with "ing", and that it's not followed by any unicode letters.
To match multiple verbs we'd have to expand this a bit. Putting it into a function. The function will find all substrings that match the specified pattern, and then put them in a string array and return it to you.
Public Function FindVerbs(ByVal Input As String) As String()
Dim Matches As MatchCollection = Regex.Matches(Input, "\p{L}+(?=ing[^\p{L}])", RegexOptions.IgnoreCase)
Dim ReturnArray(Matches.Count - 1) As String
For x = 0 To Matches.Count - 1
ReturnArray(x) = Matches(x).Value
Next
Return ReturnArray
End Function
Function example usage:
Dim Verbs() As String = FindVerbs("I am playing with my helicopter. It's flying very fast.")
Console.WriteLine(Verbs(0)) 'Prints "play"
Console.WriteLine(Verbs(1)) 'Prints "fly"
Example: http://ideone.com/6TeAmz

Best way is to replace whole word. You put in word in textbox that you want to add ing to it
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myInput As String = TextBox1.Text
Dim myOutput As String = StringToReplacePart.Replace(myInput, String.Format("{0}ing", myInput)
Label1.Text = myOutput
End Sub

Related

Parsing String into an Array (VB)

I have tried to make a program that would parse a raw list from Chrome://policy (input by RichTextbox) into a text array, then dump it into another RichTextbox. All of the raw string are exactly 32 characters long, followed by a comma. Here is the code:
Public Class Form1
Dim tempExt As String
Dim extsHandled As Integer
Dim numOfExts As Integer
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If RichTextBox1.Text = "" Then
MsgBox("Please enter the raw extensions from Chrome://policy")
Else
RichTextBox3.Text = RichTextBox1.Text
numOfExts = TextBox1.Text
Dim place As Integer = 0
Dim exts(150) As String
While extsHandled < numOfExts
tempExt = RichTextBox1.Text.Substring(0, 32)
exts(place) = tempExt
RichTextBox1.Text.Remove(0, 33)
place = place + 1
extsHandled = extsHandled + 1
End While
Dim newPlace As Integer = 0
While newPlace < numOfExts
RichTextBox2.AppendText(exts(newPlace))
newPlace = newPlace + 1
RichTextBox2.AppendText(" ")
End While
End If
End Sub
End Class
Most of it works, but it would seem something is going wrong with removing the characters from the richtextbox, as when I run it, it only parses the first part of the string over and over:
Am I doing something wrong?
If it's always like that you can do it like this:
RichTextBox3.Text = RichTextBox1.Text.Replace(",", vbNewLine)
The #3 is your result, while #1 is original right?
Ah yeah, you can count how many there simply by
RichTextBox2.Text= RichTextBox1.Text.Split({","}, StringSplitOptions.RemoveEmptyEntries).Count.ToString
This line returns a new string:
RichTextBox1.Text.Remove(0, 33)
It does not modify the textbox in place. The next iteration through the loop, you're still working with the original value, looking at the same set of 32 characters at the beginning of the string.
Additionally, nothing in this code initializes the extsHandled variable. You should turn on Option Strict, which helps catch that kind of error. Running of Option Strict off is poor practice. You should also give a meaningful name to any control you will actually reference from code.
It's not clear to me right now the exact format. If it's all on the same line (no line break characters as part of the string, even if it wraps), this should work:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If String.IsNullOrWhitespace(RichTextBox1.Text) Then
MsgBox("Please enter the raw extensions from Chrome://policy")
Exit Sub
End If
RichTextBox3.Text = RichTextBox1.Text
Dim exts() As String
Using rdr As New TextFieldParser(RichTextBox1.Text)
rdr.TextFieldType = FileIO.FieldType.Delimited
rdr.Delimiters = New String() {","}
exts = rdr.ReadFields()
End Using
For Each ext As String In exts
RichTextBox2.AppendText(ext)
Next ext
RichTextBox1.Text = ""
End Sub
The problem is this code doesn't do anything. The array is gone when the method ends. Consider making the array a property of the class, or having method that returns the array as the result.
You can also look at this, to save typing into the textbox, though it's just a starting point:
Public Function GetChromeExtensionKeys() As IEnumerable(Of String)
Dim BasePath As String =
EndEnvironment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
BasePath = Path.Combine(BasePath, "Google\Chrome\User Data")
Dim dflt As String = Path.Combine(BasePath, "Default\Extensions")
Dim profileExts() As String = Directory.GetDirectories(BasePath, "Profile *").
Select(Function(p) Path.Combine(p, "Extensions"))
Dim result As New List(Of String)()
result.AddRange(Directory.GetDirectories(dflt))
For Each folder As String In profiles
result.AddRange(Directory.GetDirectories(folder))
Next folder
Return result.Select(Function(e) Path.GetFileName(e)).Distinct()
Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For Each ext As String In GetChromeExtensionKeys()
RichTextBox2.AppendText(ext)
Next ext
End Sub

Value of type string() cannot be converted to string

I keep getting this error, I tried all I could but it still says "Value type of String() cannot be converted to string."
Here is the code:
Private Sub Label1_Click(sender As Object, e As EventArgs) Handles Label1.Click
End Sub
Sub New()
InitializeComponent()
RAN = New Random
WB = New WebClient
End Sub
Private Const IDNum As String = "https://example.com/Data.php"
Private WB As WebClient
Private RAN As Random
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Account As String() = WB.DownloadString(IDNum).Split(Environment.NewLine)
AccSplit(Account(RAN.Next(1, Account.Length)))
End Sub
Private Sub AccSplit(ByVal Account As String)
TextBox2.Text = Account.Split()
End Sub
When you call Split here:
TextBox2.Text = Account.Split()
You are getting a String array back. Calling Split with no arguments will split the String on whitespace characters. For instance, this:
Dim arr = "Hello World".Split()
is equivalent to this:
Dim arr = {"Hello", "World"}
The Text property of a TextBox is type String, so you can't assign a String array to it. That doesn't make sense. If you want to fry an egg, do you put am egg carton in the pan? The correct course of action depends on what you're actually trying to achieve. If you just want that String displayed in the TextBox then do this:
TextBox2.Text = Account
You could also do this:
TextBox2.Lines = Account.Split()
to display the array with the elements on separate lines in the TexTbox, which assumes that you have set its Multiline property to True.
TextBox2.Text is a string. The string.Split() function returns an array of strings (shown by Visual Studio as a string()). Those types don't match up. You can't just assign an array to a string. I might ask if you wanted this:
TextBox2.Text = String.Join(",", Account.Split())
That will at least compile. But it makes no sense... why split a string, just to join it back again?

How do I optimize my code - vb.net

I have a working program, but it's like Frankenstein - parts of other programs put together, that may be redundant. Here's what I'm trying to do:
Find a string inside a binary file & from that location to the EOF dump the contents into a string.
Here is my code:
Imports System.IO
Public Class Form1
Dim b() As Byte = IO.File.ReadAllBytes("C:\data.bin")
Dim encodme As New System.Text.ASCIIEncoding
Dim SearchString As String = "xyzzy"
Dim bSearch As Byte() = encodme.GetBytes(SearchString)
Dim bFound As Boolean = True
Dim oneByte As Byte
Dim fileData As New IO.FileStream("C:\data.bin", FileMode.Open, FileAccess.Read)
Dim strMessage As String
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
For i As Integer = 0 To b.Length - bSearch.Length - 1
If b(i) = bSearch(0) Then
bFound = True
For j As Integer = 0 To bSearch.Length - 1
If b(i + j) <> bSearch(j) Then
bFound = False
Exit For
End If
Next
If bFound Then
fileData.Seek(i + 5, SeekOrigin.Begin)
strMessage = ""
For r As Integer = (i + 5) To fileData.Length() - 1
oneByte = fileData.ReadByte()
strMessage = strMessage + Chr(oneByte)
Next r
MsgBox(strMessage)
Else
MsgBox("File Doesn't have string")
Exit Sub
End If
End If
Next
End Sub
End Class
When looking for performance, it is best to avoid trying to walk through this kind of thing byte by byte. Instead you should use the facilities .NET provides you with. This example uses RegEx to find all matches of a string in any file, returning each match with everything that follows it until the next match or the end of the file in a UTF-8 string:
Imports System.IO
Imports System.Text
Imports System.Text.RegularExpressions
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim matches = FindStringMatchesInFile("C:\Infinite Air\snowboarding.exe", "data")
For Each m In matches
...
Next
End Sub
Private Function FindStringMatchesInFile(filename As String,
searchString As String) As List(Of String)
Dim output As New List(Of String)
Dim reader = New StreamReader(filename, Encoding.UTF8)
Dim re = New Regex(String.Format("{0}(?:(?!{0}).)*", searchString),
RegexOptions.Singleline Or RegexOptions.IgnoreCase,
Regex.InfiniteMatchTimeout)
Dim matches = re.Matches(reader.ReadToEnd())
For Each m As Match In matches
output.Add(m.ToString())
Next
Return output
End Function
End Class
The RegEx pattern definition is the following:
Matches the characters {searchString} literally (case insensitive)
Non-capturing group (?:(?!{searchString}).)*
* Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
Negative Lookahead (?!{searchString})
Assert that the Regex below does not match
Matches the characters {searchString} literally (case insensitive)
. matches any character
Global pattern flags
g modifier: global. All matches (don't return after first match)
s modifier: single line. Dot matches newline characters
i modifier: case insensitive.

Operation '&' is not defined for string and integer. For some reason it won't work

Dim numbers(9) As Integer
Dim Card As String
Dim CardInfo As Integer
Const ListSize = 9
Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click
listOutput.Items.Clear()
'populate the numbers array
For i As Integer = 0 To 9
numbers(i) = txtValue.Text
Card = txtCard.Text
CardInfo = numbers & Card
listOutput.Items.Add(CardInfo)
Next
For i = 0 To ListSize
Next i
txtSearchValue.Focus()
End Sub
Your problem is here:
numbers(i) = txtValue.Text
Numbers is an array of integer and txtValue.Textis a String.
You cannot save a String into an integer. My guess is that you want the value of that string. If its a "23" you want the number 23. For that you need to parse.
numbers(i) = Integer.Parse(txtValue.Text)
That will save the value of your string into the int.
Important:
If txtValue have a not valid text, something that's not a number it will throw an exeption. And we don't want that. So we can use TryParse:
Integer.TryParse(txtValue.Text,numbers(i))
If you are sure that it will always have a valid number on the txtValue, you can use the standart Parse, if not, use TryParse
First of all, it's not complaining about a String + Integer. It's complaining about String + Integer(). The numbers variable used with the & operator in that code is an array, which doesn't just concatenate with strings. The subscript is missing.
But you can greatly reduce all that code anyway:
Const ListSize = 9
Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click
Dim items = Enumerable.Range(0, ListSize).Select(Function (i) String.Format("{0} {1}", txtCard.Text, i)).ToArray()
listOutput.Items.Clear()
listOutput.Items.AddRange(items)
txtSearchValue.Focus()
End Sub

How to do format check on string?vb.net

How do check that a string only consists of letters?########################################################################################################################################################################################################################################################
Here's a way to check if a string contains only letters:
Dim text As String = "abcd"
Dim flag As Boolean = text.AsEnumerable().All(Function(c As Char) Char.IsLetter(c))
You would use String.Contains() This exsplains how to use it, http://vb.net-informations.com/string/vb.net_String_Contains.htm
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim str As String
str = "VB.NET TOP 10 BOOKS"
If str.Contains("TOP") = True Then
MsgBox("The string Contains() 'TOP' ")
Else
MsgBox("The String does not Contains() 'TOP'")
End If
End Sub
End Class
Edit: I'm not sure why your post includes a lot of #'s, is it an example of the text your looking to check over? :3
Public Function isValid(ByVal str As String) As Boolean
Dim pattern As String = "^[a-zA-Z\s]+$"
Dim reg As New Regex(pattern)
Return reg.IsMatch(str)
End Function
This could possibly be the solution your after.
You want to use a regular expression like in this question:
C# Regex: Checking for "a-z" and "A-Z"
The vb should be very similar:
private function isValid(byval str as String) as Boolean
return Regex.IsMatch(str, #"^[a-zA-Z]+$")
End Function