Please be easy on me guys as I'm still learning.
The following code:
Imports System.Console
Module Module1
Sub Main()
Dim num As Integer
Dim name As String
num = 1
name = "John"
WriteLine("Hello, {0}", num)
WriteLine("Hello, {0}", name)
WriteLine("Hello, {0}", 1)
WriteLine("Hello, {0}", "John")
WriteLine("5 + 5 = {0}", 5 + 5)
WriteLine()
End Sub
End Module
has the same output as this code:
Imports System.Console
Module Module1
Sub Main()
Dim num As Integer
Dim name As String
num = 1
name = "John"
WriteLine("Hello, " & num)
WriteLine("Hello, " & name)
WriteLine("Hello, " & 1)
WriteLine("Hello, " & "John")
WriteLine("5 + 5 = " & 5 + 5)
WriteLine()
End Sub
End Module
Both output:
Hello, 1
Hello, John
Hello, 1
Hello, John
5 + 5 = 10
I looked everywhere and couldn't find the answer.
When to use "{0}, {1}, ... etc"? and when to use "&"?
Which is better? And why?
With {0} you're specifying a format placeholder, whereas with & you're just concatenating the string.
Using format placeholders
Dim name As String = String.Format("{0} {1}", "James", "Johnson")
Using string concatenation
Dim name As String = "James" & " " & "Johnson"
What you're seeing here are two very different expressions that just so happen to evaluate to the same output.
The & operator in VB.Net is the string concatenation operator. It essentially works by converting both the left and right side of the expression to a String and them adding them together. This means all the below operations are roughly equivalent
"Hello " & num
"Hello " & num.ToString()
"Hello " & CStr(num)
The {0} is a feature of the .Net APIs. It represents a position within a string which will later be replaced with a value. The {0} refers to the first value passed to the function, {1} the second and so on. This means that all the below operations are roughly equivalent
Console.WriteLine("Hello {0}!", num)
Console.WriteLine("Hello " & num & "!")
The reason you see the same output is because putting {0} at the end of the string is almost exactly the same as a string concatenation of the 2 values.
Using {N} is called Composite Formatting. One advantage, besides readability, is the fact that you can easily set alignment and format properties. Example from the MSDN link:
Dim MyInt As Integer = 100
Console.WriteLine("{0:C}", MyInt)
' The example displays the following output
' if en-US is the current culture:
' $100.00
{0} is a placeholder that is used in conjunction with String.Format in order to have a more readable and performant string substitutions. Several method calls, including WriteLine, have implicit calls to String.Format.
The problem with using concatenation is that each concat operation will create a new string, which consumes memory.
If you are performing a lot of substitutions, then the best performance will be to use System.Text.StringBuilder instead.
Related
I have to answer this in Visual Basic.I actually don't have any idea how to solve this, our teacher barely teaches us practical stuff. I have to submit this assignment by today too.
I have tried to do solve it and searched the internet for it, but I could barely understand it.
Here is some code you can build upon:
Public Sub AddTwoNumbers()
Dim FirstNumber As String = Convert.toInt32(InputBox("Enter the first number.")) 'Get the first number
Dim SecondNumber As String = Convert.toInt32InputBox("Enter the second number.")) 'Get the second number
Dim Result As Integer = 0 'Used to store the result in
'Now perform the calculation.
Result = FirstNumber + SecondNumber
'Then show the result in a MessageBox
MessageBox.Show("The result is: " & Result.ToString())
End Sub
Here's an example using Integer.TryParse():
Dim value1, value2 As Integer
Dim response As String = InputBox("Enter first Integer:")
If Integer.TryParse(response, value1) Then
response = InputBox("Enter second Integer:")
If Integer.TryParse(response, value2) Then
Dim sum As Integer = value1 + value2
MessageBox.Show("The sum of " & value1 & " and " & value2 & " is " & sum)
Else
MessageBox.Show(response & " is not a valid Integer!")
End If
Else
MessageBox.Show(response & " is not a valid Integer!")
End If
Am using Replace("~", chr(34)) but output am getting is this
Output:
{""Code"":""101"",""Description"":""demo - account""}
This is existing string:
{~Code~:~101~,~Description~:~demo - account~}
Desired output i want is this: {"Code":"101","Description":"demo - account"}
You can test the following code:
Sub ReplaceInString()
Dim original As String = "{~Code~:~101~,~Description~:~demo - account~}"
Dim replaced As String = original.Replace("~", """")
Console.WriteLine("Original string is: " & original)
Console.WriteLine("Result string is: " & replaced)
End Sub
If you want to specify the " char, you need to write it twice between other double quotes, """".
From my test, I get the result you expect.
I want to take a name in First Last format and change it to Last, First. I know I could to this with a formula but I want to be complicated.
Please let me know if you see any red flags in my code, or suggestions for improvements.
Function LastFirst(Name_FL As String)
'This only works if there is a single space in the cell - Will Error If Spaces <> 1
Length = Len(Name_FL) 'Establishes Length of String
Spaces = Length - Len(Application.WorksheetFunction.Substitute(Name_FL, " ", "")) 'Number of spaces
If Spaces <> 1 Then
LastFirst = "#SPACES!#" 'Error Message
Else
SpaceLocation = Application.WorksheetFunction.Find(" ", Name_FL, 1) 'Location of space
Last = Right(Name_FL, Length - SpaceLocation) 'Establishes Last Name String
First = Left(Name_FL, SpaceLocation) 'Establishes First Name String
LastFirst = Application.WorksheetFunction.Proper(Last & ", " & First) 'Puts it together
End If
End Function 'Ta-da
You could simplify it to:
Function LastFirst(Name_FL As String) As String
If (Len(Name_FL) - Len(Replace(Name_FL, " ", ""))) > 1 Then
LastFirst = "#SPACES#"
Else
LastFirst = StrConv(Split(Name_FL, " ")(1) & ", " & Split(Name_FL, " ")(0), vbProperCase)
End If
End Function
The logic here is:
If there is more than 1 space, return the error string #SPACES#
If there is 1 space, the split the string using " " as a delimiter.
Use the second index of the Split array, add ", " and use the first index of the split array.
Use StrConv() to convert it all to proper case.
You might also want to add another check for no spaces:
If InStr(Name_FL, " ") > 0 Then
'// There is a space in the string
Else
'// There is no space in the string
End If
Which can also be tested for by slightly changing the logic of the above example:
Function LastFirst(Name_FL As String) As String
If (Len(Name_FL) - Len(Replace(Name_FL, " ", ""))) = 1 Then
LastFirst = StrConv(Split(Name_FL, " ")(1) & ", " & Split(Name_FL, " ")(0), vbProperCase)
Else
LastFirst = "#SPACES#"
End If
End Function
Further elaboration on functions:
You can see I've used some VBA functions here in place of your WorksheetFunction methods.
Len() returns the Length of a string.
Replace() does what it says on the tin - replaces a given string with another.
StrConv() Converts a String to a respective case (e.g. vbProperCase).
Split() Creates a zero-based single dimension array from a string, by Splitting it on a given delimiter.
Finally - Don't forget to specify a return value in your function header:
Function LastFirst(Name_FL As String)As String<~~ return type
I'm trying to convert a string that contains someones name as "Last, First" to "First Last".
This is how I am doing it now:
name = name.Trim
name = name.Substring(name.IndexOf(",") + 1, name.Length) & " " & name.Substring(0, name.IndexOf(",") - 1)
When I do this I get the following error:
ArgumentOutOfRangeException was unhandled
Index and length must refer to a location within the string
Parameter name: length
Can someone explain why I am getting this error and how I should be doing this?
You are getting error on this:
name.Substring(name.IndexOf(",") + 1, name.Length)
name.Length should have subtracted with the length of the string before the comma.
The best way for that is to split the string.
Dim oFullname as string = "Last, First"
Dim oStr() as string = oFullname.split(","c)
oFullname = oStr(1).trim & " " & oStr(0).trim
MsgBox (oFullname)
The second parameter for String.Substring is the length of the substring, not the end position. For this reason, you're always going to go out of bounds if you do str.Substring(n, str.Length) with n > 0 (which would be the whole point of a substring).
You need to subtract name.IndexOf(",") + 1 from name.Length in your first substring. Or just split the string, as the others have suggested.
simply ,you only need to split the string
Dim originalName As String = "Last,First"
Dim parts = name.Split(","C)
Dim name As String = parts(1) & " " & parts(0)
If you're using the Unix command line--like the terminal on a Mac--you can do it like this:
Let's say that you have a file containing your last-comma-space-first type names like this:
Last1, First1
Last2, First2
Last3, First3
OK, now let's save it as last_comma_space_first.txt. At this point you can use this command I came up with for your particular problem:
sed -E 's/([A-Za-z0-9]+), ([A-Za-z0-9]+)/\2 \1/g' last_comma_space_first.txt > first_space_last.txt
--->>> Scroll --->>>
You're done! Now, go check that first_space_last.txt file! ^_^ You should get the following:
First1 Last1
First2 Last2
First3 Last3
Tell your friends... Or don't...
This would work keeping to the posters format.
Name = "Doe,John"
Name = Replace(Name.Substring(Name.IndexOf(","), Name.Length - Name.IndexOf(",")) & " " & Name.Substring(0, Name.IndexOf(",")), ",", "")
Result Name = "John Doe"
I am writing a console application which requires user input of certain values. I want to disallow any letter input. The console automatically writes "Conversion from string "b" to type 'Integer' is not valid." but I want the console to display my personal message "Not a valid number, please try again." how can I do that?
I've tried many different keywords and phrases but none work. Maybe I'm doing it wrong (not unlikely) or maybe it's just meant for something else. Either way I need help.
To recap: User input in a console that only allows numbers not letters, and will display my message.
I didn't want to post my code since people always pick on it, but here it is. Please note that there MUST be an exception. It is homework and I NEED an exception and this is one way a user can screw up. Please don't tell me not to use an exception.
Module Module1
Sub Main()
Try
System.Console.WriteLine("Input up to 10 valid numbers to have them mathematically averaged.")
For Index = 0 To 9
Dim Input As IList
Input = Console.ReadLine()
Next Index
If ' here is where I want to add that numbers only Then
Throw New exception("Not a valid number, please try again.")
Else
System.Console.WriteLine("Now averaging numbers...")
Dim average As Double = (n + n + n + n + n + n + n + n + n + n) / 10
Console.WriteLine("The average of " & n & "," & n & "," & n & "," & n & "," & n & "," & n & "," & n & "," & n & "," & n & " and " & n & " is " & average & ".", "Calculation")
End If
Catch e As Exception
System.Console.WriteLine(e.Message)
End Try
End Sub
End Module
Dim inputString = Console.ReadLine
If Integer.TryParse(inputString, num) Then
DoSomething(num)
Else
Console.WriteLine("Not a valid number, please try again.")
End If
Here's one way to do it, honoring your requirements:
Module Module1
Sub Main()
System.Console.WriteLine("Input valid numbers seperated by spaces to have them mathematically averaged.")
Dim inputArray As String() = System.Text.RegularExpressions.Regex.Replace(Console.ReadLine().Trim(), "\s{2,}", " ").Split(New Char() {" "})
Dim values As New ArrayList
Dim sum As Integer
For i As Integer = 0 To inputArray.Length - 1
Try
sum = sum + Integer.Parse(inputArray(i), Globalization.NumberStyles.Integer)
values.Add(inputArray(i))
Catch ex As Exception
Console.WriteLine(String.Format("The value ""{0}"" is not a valid number and will be ignored. ExceptionMessage: {1}", inputArray(i), ex.Message))
End Try
Next
Dim average As Decimal = sum / values.Count
Console.WriteLine(vbCrLf)
Console.WriteLine(String.Format("The average of ""{0}"" is {1}", Join(values.ToArray, ", "), average))
Console.WriteLine(vbCrLf)
Main()
End Sub
End Module
Well for starters, the Try - Catch should be inside the input gathering For loop. As your program is written now, as soon as one wrong value is entered execution jumps to the catch and your program ends! If you try casting your input to an decimal you won't need to throw an exception manually, it will be thrown automatically if your input is not an decimal! Try casting the current console input as a decimal and then add that number to your list.
Dim inputNumber as Decimal = CDec(Console.ReadLine())
Input.Add(inputNumber)
Also n will be the same number every time so how you are doing it won't work (look up the basics of how a list works, how to add elements to a list and how to display list elements)