How to reverse "This is friday" to "friday is this" in vb.net in Easiest Way - vb.net

'How to reverse "This is Friday" to "Friday is this" in vb.net in Easiest Way
Dim str As String = txtremarks.Text
Dim arr As New List(Of Char)
arr.AddRange(str.ToCharArray)
arr.Reverse()
Dim a As String = ""
For Each l As Char In arr
a &= l
Next
' I saw on a few forums that to use SPLIT function. Please help

Yes you can use split. You can also use join and the reverse method:
Dim test = "This is Friday"
Dim reversetest = String.Join(" ", test.Split().Reverse)

First you'll want to split your sentence into individual words. This is where you'd use the String.Split method.
Once you have an array containing your individual words, you can reverse that array. Perhaps using Linq's Enumerable.Reverse extension method.
Finally, you can put the words back together into a string. The String.Join method allows you to join the elements of a string array back into a single string.
I'm not a VB programmer, but something like this should work:
Dim str As String = "this is friday"
Dim split As String() = str.Split(" ")
Dim result as String = String.Join(" ", split.Reverse())

Here's a way to do it in 1 line:
Dim reverse As String = "This is friday".Split().Reverse().Aggregate(Function(left, right) String.Join(" ", left, right))
Do note that this has a horrible performance overhead.

Yes, you can Split your String via " " (space) and insert results into array.
Next, read array from the end to start.
Good luck!

Try this...
Dim txt As String = "This is friday"
Dim txtarray() As String = Split(txt.Trim(), " ")
Dim result As String = ""
For x = txtarray.GetUpperBound(0) To 0 Step -1
result += txtarray(x) & " "
Next x
MsgBox(result.Trim())

Related

How to get the part inside an "[" and "]" of a string (strange behaviour)

I am trying to get the part of a string between [ and ]. So far I have this:
For Each a As String In CType(TabControl1.SelectedTab.Controls.Item(0),
RichTextBox).Text.Split(System.Environment.NewLine())
If (a.Contains("print ")) Then
Dim sData As String
sData = a.Substring(6)
Dim i, j As Integer
i = sData.IndexOf("[") + "[".Length
j = sData.IndexOf("]") - i
Dim sData1 As String
sData1 = sData.Substring(i, j)
Console.WriteLine(sData1)
End If
Next
However, if I have this:
print [Hello world!]
print [What's up world?]
then the output is this:
Hello world!
but the required output is:
Hello world!
What's up world
I.e. it will not display anything after the first time a print is found.
So why is that happening and how could I fix it?
You are not using Option Strict On which results in you not being told that Split(System.Environment.NewLine()) is truncating the CRLF to CR. The lines of a RichTextBox are separated with LF.
The easy solution would be to use the .Lines property of the RTB:
For Each a As String In CType(TabControl1.SelectedTab.Controls.Item(0), RichTextBox).Lines
U can go with regex but here's a non-regex solution
'U can also use a loop(This is a working solution)
Dim mystring = "print [Hello world]" + Environment.NewLine + "Print [What's up world?]" + ........
For Each line In mystring.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
Dim hloWorld = line.Split("[")(1)
Dim result = hloWorld.Replace("]", "")
Dim finalResult = result + Environment.NewLine
'''Do what u wanna do with ur final result
Next

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!

Parsing numbers containing commas or periods

I have three values which need to be sorted from highest to lowest value. I use the following code which works like a charm until I want to use periods "." and commas ",". If I type "1,3" it displays as I like, but if I type "1.3" it changes to 13. My end users need to be able to use both commas and periods.
How can I fix this?
Dim IntArr(2) As Decimal
IntArr(0) = TextBox1.Text
IntArr(1) = TextBox2.Text
IntArr(2) = TextBox3.Text
Array.Sort(IntArr)
Dim highestNum As Decimal
Dim Midelnum As Decimal
Dim lowestNum As Decimal
lowestNum = IntArr(0)
Midelnum = IntArr(1)
highestNum = IntArr(2)
MsgBox("Highest " & highestNum)
MsgBox("lowest " & lowestNum)
MsgBox("middel " & Midelnum)
The problem is that it's based on culture. I say this because if I enter numbers as you described, I get the opposite effect ("1,3" -> "13", etc).
Here's a quick way to change the values to match the current culture.
At the top of your class, put this:
Imports System.Globalization
Then, you can do this:
Dim IntArr(2) As Decimal
Dim nfi As NumberFormatInfo = CultureInfo.CurrentCulture.NumberFormat
Dim sep1 As String = nfi.NumberDecimalSeparator
Dim sep2 As String = If(sep1.Equals("."), ",", ".")
Dim useComma As Boolean = (TextBox1.Text.Contains(",") Or TextBox2.Text.Contains(",") Or TextBox3.Text.Contains(","))
'Replace the separator to match the current culture for parsing
Decimal.TryParse(TextBox1.Text.Replace(sep2, sep1), IntArr(0))
Decimal.TryParse(TextBox2.Text.Replace(sep2, sep1), IntArr(1))
Decimal.TryParse(TextBox3.Text.Replace(sep2, sep1), IntArr(2))
Array.Sort(IntArr)
sep1 = If(useComma, ",", ".")
sep2 = If(useComma, ".", ",")
'Reformat the results to match the user's input
Dim lowestNum As String = IntArr(0).ToString().Replace(sep2, sep1)
Dim middleNum As String = IntArr(1).ToString().Replace(sep2, sep1)
Dim highestNum As String = IntArr(2).ToString().Replace(sep2, sep1)
Dim msg As String = "Highest: {0}" & Environment.NewLine & _
"Lowest: {1}" & Environment.NewLine & _
"Middle: {2}"
msg = String.Format(msg, highestNum, lowestNum, middleNum)
MessageBox.Show(msg)
Also, since you are using .NET, you may want to skip the VB6 way of doing things. Refer to my example to see what I've used.
You could use the hack of altering the string before saving it:
TextBox.Text.Replace(".",",")
But if you want to show the original input you could have a variable to detect the entered character:
Dim isDot As Boolean = False
Dim number As String = TextBox.Text
If number.Contains(".") Then
isDot = True
End If
And in the end replace it just for purposes of displaying
If isDot Then
number.Replace(",",".")
End If
The accepted answer uses too much unnecessary string manipulation. You can use the CultureInfo object to get what you need:
Sub Main
Dim DecArr(2) As Decimal
'Select the input culture (German in this case)
Dim inputCulture As CultureInfo = CultureInfo.GetCultureInfo("de-DE")
Dim text1 As String = "1,2"
Dim text2 As String = "5,8"
Dim text3 As String = "4,567"
'Use the input culture to parse the strings.
'Side Note: It is best practice to check the return value from TryParse
' to make sure the parsing actually succeeded.
Decimal.TryParse(text1, NumberStyles.Number, inputCulture, DecArr(0))
Decimal.TryParse(text2, NumberStyles.Number, inputCulture, DecArr(1))
Decimal.TryParse(text3, NumberStyles.Number, inputCulture, DecArr(2))
Array.Sort(DecArr)
Dim format As String = "Highest: {0}" & Environment.NewLine & _
"Lowest: {1}" & Environment.NewLine & _
"Middle: {2}"
'Select the output culture (US english in this case)
Dim ouputCulture As CultureInfo = CultureInfo.GetCultureInfo("en-US")
Dim msg As String = String.Format(ouputCulture, format, DecArr(2), DecArr(1), DecArr(0))
Console.WriteLine(msg)
End Sub
This code outputs:
Highest: 5.8
Lowest: 4.567
Middle: 1.2

Add text before specific characters

str as String = " " +"thisrocks" + " "
and strArray(0) = 123456sdv :'++':
so i want to add str before the :'++':, and then
strArray(0) = 123456sdv thisrocks :'++':
Is it possible ?
What could I do to search for it ? Regex maybe ?
str and strArray will already be there from previous codes. I just want to combine it int he right place.
Using the space in between will not be helpful as the strArray(0) could also be, dsf dsv dsgvsvs svs svssd bdsb sbdfb bsbb sb s sbsfbfsbsbfs :'++': and so on.
I can't control it as they come like that from previous codes and there is no way to fix them :/
I can't generalize the question since it is not clear enough, for this occasion you can use the following code to insert a string in between these two words
Dim str As String = " " + "thisrocks" + " "
Dim strArray(10) As String
strArray(0) = "123456sdv :'++':"
strArray(0) = strArray(0).Replace(":'++':", str & ":'++':")
Output will be
"123456sdv thisrocks :'++':"
Note:
this will work as, replace :'++': with & str and add :'++': to it so :'++': will stay their for the next replacement.
You can use String.IndexOf to find where the marker :'++': is and String.Insert to insert the required data:
Dim sample As String = "123456sdv :'++':"
Dim insertData As String = " thisrocks "
Dim marker As String = ":'++':"
Dim insertPos As Integer = sample.IndexOf(marker)
If insertPos >= 0 Then
sample = sample.Insert(insertPos, insertData)
End If
Console.WriteLine(sample) ' outputs "123456sdv thisrocks :'++':"

How could I get the first and last letters from a string?

How can I get my program to take the first and last letters from an entered string?
Example: "I've been told I am a noob!"
Output: "IebntdIaman!"
I tried to use Split with no luck.
Try something like this. since you have a couple of single character words I used a conditional in order to get your desired output. I also am using the String.Split method that removes empty entries in order to prevent a zero length item, then I am taking the result and using the String.Substring Method to parse out your starting and ending chars.
Sub Main()
Dim splitChar As String() = {" "}
Dim example As String = " I've been told I am a noob!"
Dim output As String = ""
Dim result As String() = example.Split(splitChar, StringSplitOptions.RemoveEmptyEntries)
For Each item In result
If item.Length > 1 Then
output += item.Substring(0, 1) & item.Substring(item.Length - 1, 1)
Else
output += item.Substring(0, 1)
End If
Next
Console.WriteLine(output)
Console.ReadLine()
End Sub
This works nicely:
Dim example As String = "I've been told I am a noob!"
Dim result = New String( _
example _
.Split(" "c) _
.SelectMany(Function (w) _
If(w.Count() = 1, _
new Char() { w(0) }, _
New Char() { w.First(), w.Last() })) _
.ToArray())
'IebntdIaman!