How to print os.args[1:] without braces in Go? - go

When I tried to print command line arguments using
fmt.Println(os.Args[1:])
I got result like
[Gates Bill]
How can I get rid of the [] around the arguments? And Go seems to eat all the commas in the arguments, how can I get the output like
Last name, First name
Gates, Bill

You should use strings.Join for this. Try,
fmt.Printf("%s, Author of The Art of Computer Programming", strings.Join(os.Args[1:], ", "))
Join returns a string with ", " inserted between each argument.

The reason it's outputting the brackets is because you're passing a slice into the print command.
What you want to do is take each command and put them into a string to be printed as needed.
firstname := os.Args[1]
lastname := os.Args[2]
fmt.Println(lastname + ", " + firstname)
You should also take a look at the strings package as was pointed out by Chandru. There's a bunch of goodies in there to help with dealing with strings.
See: https://golang.org/pkg/strings/

Related

Regexp.escape adds weird escapes to a plain space

I stumbled over this problem using the following simplified example:
line = searchstring.dup
line.gsub!(Regexp.escape(searchstring)) { '' }
My understanding was, that for every String stored in searchstring, the gsub! would cause that line is afterwards empty. Indeed, this is the case for many strings, but not for this case:
searchstring = "D "
line = searchstring.dup
line.gsub!(Regexp.escape(searchstring)) { '' }
p line
It turns out, that line is printed as "D " afterwards, i.e. no replacement had been performed.
This happens to any searchstring containing a space. Indeed, if I do a
p(Regexp.escape(searchstring))
for my example, I see "D\\ " being printed, while I would expect to get "D " instead. Is this a bug in the Ruby core library, or did I misuse the escape function?
Some background: In my concrete application, where this simplified example is derived from, I just want to do a literal string replacement inside a long string, in the following way:
REPLACEMENTS.each do
|from, to|
line.chomp!
line.gsub!(Regexp.escape(from)) { to }
end
. I'm using Regexp.escape just as a safety measure in the case that the string being replaced contains some regex metacharacter.
I'm using the Cygwin port of MRI Ruby 2.6.4.
line.gsub!(Regexp.escape(searchstring)) { '' }
My understanding was, that for every String stored in searchstring, the gsub! would cause that line is afterwards empty.
Your understanding is incorrect. The guarantee in the docs is
For any string, Regexp.new(Regexp.escape(str))=~str will be true.
This does hold for your example
Regexp.new(Regexp.escape("D "))=~"D " # => 0
therefore this is what your code should look like
line.gsub!(Regexp.new(Regexp.escape(searchstring))) { '' }
As for why this is the case, there used to be a bug where Regex.escape would incorrectly handle space characters:
# in Ruby 1.8.4
Regex.escape("D ") # => "D\\s"
My guess is they tried to keep the fix as simple as possible by replacing 's' with ' '. Technically this does add an unnecessary escape character but, again, that does not break the intended use of the method.
This happens to any searchstring containing a space. Indeed, if I do a
p(Regexp.escape(searchstring))
for my example, I see "D\\ " being printed, while I would expect to get "D " instead. Is this a bug in the Ruby core library, or did I misuse the escape function?
This looks to be a bug. In my opinion, whitespace is not a Regexp meta character, there is no need to escape it.
Some background: In my concrete application, where this simplified example is derived from, I just want to do a literal string replacement inside a long string […]
If you want to do literal string replacement, then don't use a Regexp. Just use a literal string:
line.gsub!(from, to)

how to split long lines for fmt.sprintf

I have a very long line in fmt.Sprintf. How do I split it in the code? I don't want to put everything in a single line so the code looks ugly.
fmt.Sprintf("a:%s, b:%s ...... this goes really long")
Use string concatenation to construct a single string value on multiple lines:
fmt.Sprintf("a:%s, b:%s " +
" ...... this goes really long",
s1, s2)
The long string in this example is built at compile time because the string concatenation is a constant expression.
You can split the string at contained newlines using a raw string literal:
fmt.Sprintf(`this text is on the first line
and this text is on the second line,
and third`)
You can also use raw string literals inside backticks, like this:
columns := "id, name"
table := "users"
query := fmt.Sprintf(`
SELECT %s
FROM %s
`, columns, table)
fmt.Println(query)
There are a few caveats to this approach:
Raw strings don't parse escape sequences
All the whitespace will be preserved, so there will be a newline and then several tabs before the FROM clause in this query.
These problems can be a challenge for some, and the whitespace will produce some ugly resulting strings. However, I prefer this approach as it allows you to copy and paste long, complex SQL queries outside of your code and into other contexts, like sql worksheets for testing.
Since you're using Sprintf already (meaning you'll have a string like "this is the string with %s placeholders in it") you could just add more place holders to the string and then put the values you'd like there on their own lines like;
fmt.Sprintf("This %s is so long that I need %s%s%s for the other three strings,
"string",
"some super long statement that I don't want to type on 50 lines",
"another one of those",
"yet another one of those")
Another option is just to use string concatenation like "string 1" + "string 2".
Another option is strings.Builder:
package main
import (
"fmt"
"strings"
)
func main() {
b := new(strings.Builder)
fmt.Fprint(b, "North")
fmt.Fprint(b, "South")
println(b.String() == "NorthSouth")
}
https://golang.org/pkg/strings#Builder
Why don't you split it out:
fmt.Sprintf("a:%s, b:%s ", x1, x2)
fmt.Sprintf("...... ")
fmt.Sprintf("this goes really long")
Or you can split them out with the plus sign as indicated by MuffinTop.

How to print out non-contiguous sections of the slice in Go?

Wondering if there is a way to print out non contiguous portions of slice in Gol?
Example:
words := []string{"Mary","had","a","little","lamb"}
and I want to print out "Mary" and "lamb" from the slice?
Something along the lines of:
fmt.Printf("%s\n", words[0],[5])
...which obviously this won't work... Is there a way ? :(
Thanks a lot!!
You can index into the slice, you just are doing it wrong.
fmt.Printf("%s %s\n", words[0], words[5])
Your syntax for indexing didn't work because the second variable was just the index stuff without words. Additionally your format string was wrong, a single %s which means Printf is only expecting a single argument after that. Gotta have one formatter per arg.

How do you print a dollar sign $ in Dart

I need to actually print a Dollar sign in Dart, ahead of a variable. For example:
void main()
{
int dollars=42;
print("I have $dollars."); // I have 42.
}
I want the output to be: I have $42. How can I do this? Thanks.
Dart strings can be either raw or ... not raw (normal? cooked? interpreted? There isn't a formal name). I'll go with "interpreted" here, because it describes the problem you have.
In a raw string, "$" and "\" mean nothing special, they are just characters like any other.
In an interpreted string, "$" starts an interpolation and "\" starts an escape.
Since you want the interpolation for "$dollars", you can't use "$" literally, so you need to escape it:
int dollars = 42;
print("I have \$$dollars.");
If you don't want to use an escape, you can combine the string from raw and interpreted parts:
int dollars = 42;
print(r"I have $" "$dollars.");
Two adjacent string literals are combined into one string, even if they are different types of string.
You can use a backslash to escape:
int dollars=42;
print("I have \$$dollars."); // I have $42.
When you are using literals instead of variables you can also use raw strings:
print(r"I have $42."); // I have $42.

Splitting A String In Two Parts(REALBASIC)

I am trying to split a string at the character ":" but cant create two separate strings from the split. If somebody could help me, I would appreciate it.
In RealBasic, the Split method doesn't create two (or more) separate strings but rather a single string array.
Dim s() As String = Split("Zero:One:Two", ":")
's() now contains the substrings like so:
's(0) = "Zero"
's(1) = "One"
's(2) = "Two"
Actually, the code is incorrect. It should be:
Dim s() As String = Split("Zero:One:Two", ":")
If you don't pass in the delimiter it assumes a space which wouldn't work in this case.
The online docs are at http://docs.realsoftware.com/index.php/Split
Split is best for actually splitting the text, but you can also use the string-manipulation methods: Left, Right, Mid and InStr.

Resources