Compare two strings with wildcard - vb.net

I want to compare two strings. I want to be able to say that s1 is equal to s2 because of the common word "hello". any suggestions on how to achieve this with or without another function?
s1: hello
s2: hello world
if s1 = s2 then
..do something
else
..do something
end if

It sounds as if you want to compare substrings, you can use String.Contains:
Dim s1 = "hello"
Dim s2 = "hello world"
Dim s2ContainsHello As Boolean = s2.Contains(s1) ' True
or (if you want to ignore the case) String.IndexOf which returns -1 if it wasn't found:
s2 = "Hello World"
s2ContainsHello = s2.IndexOf(s1, StringComparison.InvariantCultureIgnoreCase) >= 0 ' Still True
a third option in VB.NET is to use the Like operator (which also is case-sensitive by default):
s2ContainsHello = s2 like "*" & s1 & "*"
The Like-operator supports wild-cards:
Characters in pattern Matches in string
? Any single character
* Zero or more characters
# Any single digit (0–9)
[charlist] Any single character in charlist
[!charlist] Any single character not in charlist

If you're just looking for whether or not both strings have "hello" somewhere in them
If s1.Contains("hello") AndAlso s2.Contains("hello") Then
'do something
Else
'do something else
End If

Related

The Use of Regex.Replace with a pattern

I have a problem with replacing a number in a string.
The code is:
Dim Searchstring As String= "2 7 12 33 4 15 22 30 15"
Dim Pattern As String= "^([0-9]$)"
Dim Match As String = Val(TextBox1.Text)
Dim ReplacementString As String = "0"
Dim rgx As Regex = New Regex(pattern)
Dim NewString As String
NewString = Regex.Replace(Searchstring, Match, ReplacementString)
RichTextBox2.Text = NewString
The problem is that when I input a number, say "2", in the textbox and run the program, the replace will be as follows in the richtextbox2.text: 0 7 10 33 4 15 00 30 15 instead of 0 7 12 33 4 15 22 30 15
But when I input the number of "22" or "12" then only these numbers will be replaced and that is okay.
So how can I find a pattern that replaces only the number "2" if I want that and only that, and not change the "12" or "22"?
Please can you help me with this case?
The appropriate pattern would be ^([0-9]+) as it would get the first digits and replace them with a 0. Actually, this '$' character represents the end of a string. If you only need to replace the first number, it shouldn't be there.
The '+' character means "One ore more from the previous pattern", then it will search for one or more digits in the "[0-9]" scope from the beginning of the text and capture only the digits.
You need to tell it how to delimit the item you want to replace, in this case the "word boundary"* entity \b will work:
Dim searchstring As String = "2 7 12 33 4 15 22 30 15"
Dim match As String = TextBox1.Text
Dim pattern = "\b" & Regex.Escape(match) & "\b"
Dim rgx As Regex = New Regex(pattern)
Dim replacementString As String = "0"
Dim newString = rgx.Replace(searchstring, replacementString)
RichTextBox2.Text = newString
I used Regex.Escape on the search term in case you want to replace something like a . or ?, which have special meanings in regular expressions; escaping them removes the special meaning and uses them as ordinary characters.
You can see that it replaces only the "2" when you enter "2" in the TextBox:
and it replaces both occurrences of "15" when you tell it to:
* What is a word boundary in regex?
To find any number in the string, you can use \b to denote the beginning or end of a word (i.e., a sequence of letters, digits and underscores).
Example: replace only the number 12:
\b12\b
This will not replace, e.g., in 123 or 412.
While I will not disagree with the answers that have been presented, I will assert that the easiest and most obvious choice would be to use built-in .NET methods to manipulate your string.
Your input is a string that contains numbers delimited by spaces. You then want to replace an exact numeric match with some replacement.
You can do this by splitting the string, looping over the array, modifying the currently iterated items that match your value, and then joining them back:
Dim searchString As String = "2 7 12 33 4 15 22 30 15"
Dim replacementString As String = "0"
If (Not Integer.TryParse(TextBox1.Text, Nothing)) Then
MessageBox.Show("Please enter a valid integer.")
Return
End If
Dim searchStringCollection() As String = searchString.Split(" "c)
For index As Integer = 0 To searchStringCollection.Length - 1
If (searchStringCollection(index) = TextBox1.Text) Then
searchStringCollection(index) = replacementString
End If
Next
Dim newString As String = String.Join(" ", searchStringCollection)
Fiddle: https://dotnetfiddle.net/dZfsy6

VB.NET - Delete excess white spaces between words in a sentence

I'm a programing student, so I've started with vb.net as my first language and I need some help.
I need to know how I delete excess white spaces between words in a sentence, only using these string functions: Trim, instr, char, mid, val and len.
I made a part of the code but it doesn't work, Thanks.
enter image description here
Knocked up a quick routine for you.
Public Function RemoveMyExcessSpaces(str As String) As String
Dim r As String = ""
If str IsNot Nothing AndAlso Len(str) > 0 Then
Dim spacefound As Boolean = False
For i As Integer = 1 To Len(str)
If Mid(str, i, 1) = " " Then
If Not spacefound Then
spacefound = True
End If
Else
If spacefound Then
spacefound = False
r += " "
End If
r += Mid(str, i, 1)
End If
Next
End If
Return r
End Function
I think it meets your criteria.
Hope that helps.
Unless using those VB6 methods is a requirement, here's a one-line solution:
TextBox2.Text = String.Join(" ", TextBox1.Text.Split(New Char() {" "c}, StringSplitOptions.RemoveEmptyEntries))
Online test: http://ideone.com/gBbi55
String.Split() splits a string on a specific character or substring (in this case a space) and creates an array of the string parts in-between. I.e: "Hello There" -> {"Hello", "There"}
StringSplitOptions.RemoveEmptyEntries removes any empty strings from the resulting split array. Double spaces will create empty strings when split, thus you'll get rid of them using this option.
String.Join() will create a string from an array and separate each array entry with the specified string (in this case a single space).
There is a very simple answer to this question, there is a string method that allows you to remove those "White Spaces" within a string.
Dim text_with_white_spaces as string = "Hey There!"
Dim text_without_white_spaces as string = text_with_white_spaces.Replace(" ", "")
'text_without_white_spaces should be equal to "HeyThere!"
Hope it helped!

How does the Val() function in VB.NET work?

I have an assignment in VB.NET that I'm stuck with at the moment. Would love some help.
The question is this: You enter random characters into a textbox, for example 12ab3c4d5efgh, and at the click of a button, it must sort the characters in the textbox into 2 separate Labels, depending on whether or not the 'character' is a number or letter. So, continuing the example, Label1 must show '12345' and Label 2 must show 'abcdefgh'. I hope I made myself clear enough.
I was asked to use the Val() function but I really have no clue. Could someone please help? :D
This creates one string with the digits and one with the letters. Characters that are not digits or letters are ignored.
Dim chars As String = "12ab3c4d5efgh"
Dim nums As String = chars.Where(Function(c) Char.IsDigit(c)).ToArray
Dim lets As String = chars.Where(Function(c) Char.IsLetter(c)).ToArray
If you have to use Val() something like this would do. But be careful: Val("0") also returns 0.
Dim numbers As String = String.Empty
Dim letters As String = String.Empty
Dim sourceString As String = "12ab3c4d50efgh"
For Each c As Char In sourceString
If Val(c) = 0 And c <> "0" Then letters &= c Else numbers &= c
Next
Console.WriteLine("Numbers: " & numbers)
Console.WriteLine("Letters: " & letters)
Console.ReadKey()

Comparing character only to character at end of string

I am writing a program in Visual Basic 2010 that lists how many times a word of each length occurs in a user-inputted string. Although most of the program is working, I have one problem:
When looping through all of the characters in the string, the program checks whether there is a next character (such that the program does not attempt to loop through characters that do not exist). For example, I use the condition:
If letter = Microsoft.VisualBasic.Right(input, 1) Then
Where letter is the character, input is the string, and Microsoft.VisualBasic.Right(input, 1) extracts the rightmost character from the string. Thus, if letter is the rightmost character, the program will cease to loop through the string.
This is where the problems comes in. Let us say the string is This sentence has five words. The rightmost character is an s, but an s is also the fourth and sixth character. That means that the first and second s will break the loop just as the others will.
My questions is whether there is a way to ensure that only the last s, or whatever character is the last one in the string can break the loop.
There are a few methods you can use for this, one as Neolisk shows; here are a couple of others:
Dim breakChar As Char = "s"
Dim str As String = "This sentence has five words"
str = str.Replace(".", " ")
str = str.Replace(",", " ")
str = str.Replace(vbTab, " ")
' other chars to replace
Dim words() As String = str.ToLower.Split(New Char() {" "}, StringSplitOptions.RemoveEmptyEntries)
For Each word In words
If word.StartsWith(breakChar) Then Exit For
Console.WriteLine("M1 Word: ""{0}"" Length: {1:N0}", word, word.Length)
Next
If you need to loop though chars for whatever reason, you can use something like this:
Dim breakChar As Char = "s"
Dim str As String = "This sentence has five words"
str = str.Replace(".", " ")
str = str.Replace(",", " ")
str = str.Replace(vbTab, " ")
' other chars to replace
'method 2
Dim word As New StringBuilder
Dim words As New List(Of String)
For Each c As Char In str.ToLower.Trim
If c = " "c Then
If word.Length > 0 'support multiple white-spaces (double-space etc.)
Console.WriteLine("M2 Word: ""{0}"" Length: {1:N0}", word.ToString, word.ToString.Length)
words.Add(word.ToString)
word.Clear()
End If
Else
If word.Length = 0 And c = breakChar Then Exit For
word.Append(c)
End If
Next
If word.Length > 0 Then
words.Add(word.ToString)
Console.WriteLine("M2 Word: ""{0}"" Length: {1:N0}", word.ToString, word.ToString.Length)
End If
I wrote these specifically to break on the first letter in a word as you ask, adjust as needed.
VB.NET code to calculate how many times a word of each length occurs in a user-inputted string:
Dim sentence As String = "This sentence has five words"
Dim words() As String = sentence.Split(" ")
Dim v = From word As String In words Group By L = word.Length Into Group Order By L
Line 2 may need to be adjusted to remove punctuation characters, trim extra spaces etc.
In the above example, v(i) contains word length, and v(i).Group.Count contains how many words of this length were encountered. For debugging purposes, you also have v(i).Group, which is an array of String, containing all words belonging to this group.

How to find which delimiter was used during string split (VB.NET)

lets say I have a string that I want to split based on several characters, like ".", "!", and "?". How do I figure out which one of those characters split my string so I can add that same character back on to the end of the split segments in question?
Dim linePunctuation as Integer = 0
Dim myString As String = "some text. with punctuation! in it?"
For i = 1 To Len(myString)
If Mid$(entireFile, i, 1) = "." Then linePunctuation += 1
Next
For i = 1 To Len(myString)
If Mid$(entireFile, i, 1) = "!" Then linePunctuation += 1
Next
For i = 1 To Len(myString)
If Mid$(entireFile, i, 1) = "?" Then linePunctuation += 1
Next
Dim delimiters(3) As Char
delimiters(0) = "."
delimiters(1) = "!"
delimiters(2) = "?"
currentLineSplit = myString.Split(delimiters)
Dim sentenceArray(linePunctuation) As String
Dim count As Integer = 0
While linePunctuation > 0
sentenceArray(count) = currentLineSplit(count)'Here I want to add what ever delimiter was used to make the split back onto the string before it is stored in the array.'
count += 1
linePunctuation -= 1
End While
If you add a capturing group to your regex like this:
SplitArray = Regex.Split(myString, "([.?!])")
Then the returned array contains both the text between the punctuation, and separate elements for each punctuation character. The Split() function in .NET includes text matched by capturing groups in the returned array. If your regex has several capturing groups, all their matches are included in the array.
This splits your sample into:
some text
.
with punctuation
!
in it
?
You can then iterate over the array to get your "sentences" and your punctuation.
.Split() does not provide this information.
You will need to use a regular expression to accomplish what you are after, which I infer as the desire to split an English-ish paragraph into sentences by splitting on punctuation.
The simplest implementation would look like this.
var input = "some text. with punctuation! in it?";
string[] sentences = Regex.Split(input, #"\b(?<sentence>.*?[\.!?](?:\s|$))");
foreach (string sentence in sentences)
{
Console.WriteLine(sentence);
}
Results
some text.
with punctuation!
in it?
But you are going to find very quickly that language, as spoken/written by humans, does not follow simple rules most of the time.
Here it is in VB.NET for you:
Dim sentences As String() = Regex.Split(line, "\b(?<sentence>.*?[\.!?](?:\s|$))")
Once you've called Split with all 3 characters, you've tossed that information away. You could do what you're trying to do by splitting yourself or by splitting on one punctuation mark at a time.