Go StartsWith(str string) - string

Is there a StartsWith(str1, str2 string) function that can check if str1 is a prefix of str2 in Go language?
I want a function similar to the Java's startsWith().

The strings package has what you are looking for. Specifically the HasPrefix function: http://golang.org/pkg/strings/#HasPrefix
Example:
fmt.Println(strings.HasPrefix("my string", "prefix")) // false
fmt.Println(strings.HasPrefix("my string", "my")) // true
That package is full of a lot of different string helper functions you should check out.

For Example
If you want to check if a string starts with a dot
package main
import "strings"
func main() {
str := ".com"
fmt.Println(strings.HasPrefix(str, "."))
}
Terminal:
$ true

Related

How replace a string only if not contains in another string? [duplicate]

Is there any function/procedure as ReplaceString but for whole words on Delphi? I just need to replace substring to the new one when it's a whole word. For example:
substring - > newstring
substring, -> newstring
substring123 -> substring
You can use the built-in regex library to do this. For example:
{$APPTYPE CONSOLE}
uses
System.RegularExpressions;
const
InputString = 'a Substring, substring123, some more text';
begin
Writeln(TRegEx.Replace(InputString, '\bsubstring\b', 'newstring', [roIgnoreCase]));
end.

How do I insert a string into another string in Lua?

Is there a function in Lua that returns a string inserted into another one on given position?
For example string.insert(str1, str2, pos).
Using it: string.insert('Hello World!', 'My ', 6) becomesHello My World! and so on.
There is no such function in the standard Lua library. But it's easy to write one:
function string.insert(str1, str2, pos)
return str1:sub(1,pos)..str2..str1:sub(pos+1)
end
Note how it automatically handles negative positions (*), which count from the end of the string, as most other string functions do.
(*) it needs a small change to make pos=-1 work.

How to check whether a string contains a substring in Kotlin?

Example:
String1 = "AbBaCca";
String2 = "bac";
I want to perform a check that String1 contains String2 or not.
Kotlin has stdlib package to perform certain extension function operation over the string, you can check this method it will check the substring in a string, you can ignore the case by passing true/false value. Refer this link
"AbBaCca".contains("bac", ignoreCase = true)
The most idiomatic way to check this is to use the in operator:
String2 in String1
This is equivalent to calling contains(), but shorter and more readable.
You can do it by using the "in" - operator, e.g.
val url : String = "http://www.google.de"
val check : Boolean = "http" in url
check has the value true then. :)
See the contains method in the documentation.
String1.contains(String2);
Kotlin has a few different contains function on Strings, see here: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/contains.html.
If you want it to be true that string2 is contained in string1 (ie you want to ignore case), they even have a convenient boolean argument for you, so you won't need to convert to lowercase first.
For anyone out there like me who wanted to do this for a nullable String, that is, String?, here is my solution:
operator fun String?.contains(substring:String): Boolean {
return if (this is String) {
// Need to convert to CharSequence, otherwise keeps calling my
// contains in an endless loop.
val charSequence: CharSequence = this
charSequence.contains(substring)
} else {
false
}
}
// Uses Kotlin convention of converting 'in' to operator 'contains'
if (shortString in nullableLongString) {
// TODO: Your stuff goes here!
}

golang convert "type []string" to string

I see some people create a for loop and run through the slice as to create a string, is there an easier way to convert a []string to a string?
Will sprintf do it?
You can use strings.Join(arr \[\]string, separator string) string.
This is a simple example, which you can paste into the main function:
stringArray := []string {"Hello","world","!"}
justString := strings.Join(stringArray," ")
fmt.Println(justString)
And link to working example on playground.
Or using very simple function
simple function
Will Sprint do it?
Yes indeed!
Here is another way to convert to a string if all you care about is that it is a string and not specifically how it looks (see answers above with strings.Join for a little more flexibility).
The advantage of this method (or variations such as Sprintf), is it will work with (almost) every other data such as maps and structs and any custom type that implements the fmt.Stringer inteface.
stringArray := []string {"Hello","world","!"}
justString := fmt.Sprint(stringArray)
Here is a link to a working example.
It can be done easily using Join function by importing strings package. You need to pass the slice of strings and the separator you need to separate the elements in the string. (examples: space or comma)
func Join(elems []string, sep string) string
Example Code :
package main
import (
"fmt"
"strings"
)
func main() {
sliceStr := []string{"a","b","c","d"}
str := strings.Join(sliceStr,", ")
fmt.Println(str)
}
//output: a, b, c, d
If you don't care about the separator, you can use path:
package main
import "path"
func main() {
a := []string{"south", "north"}
s := path.Join(a...)
println(s == "south/north")
}
https://golang.org/pkg/path#Join
package main
import (
"fmt"
"reflect"
"strings"
)
func main() {
str1 := []string{"Trump", "In", "India", "On", "Feb 25"}
fmt.Println(str1)
fmt.Println(reflect.TypeOf(str1))
str2 := strings.Join(str1, " ")
fmt.Println(str2)
fmt.Println(reflect.TypeOf(str2))
str3 := strings.Join(str1, ", ")
fmt.Println(str3)
fmt.Println(reflect.TypeOf(str3))
}
Below is the ouput of the above program :-
go run hello.go
[Trump In India On Feb 25]
[]string
Trump In India On Feb 25
string
Trump, In, India, On, Feb 25
string
In the above code, first, we have defined a slice of string and then use the reflect package to determine the datatype of the slice.
We have imported the “strings” module. With strings.Join() method, and we combine all elements of a string slice into a string. So, Golang string.Join() function that converts slice to string. We have passed the space(” “) as a delimiter. So we will join the slice elements by space.
The second argument to strings.Join() is the delimiter. For no delimiter, please use an empty string literal.
In the next step, we have again used the TypeOf() function to check the data type.
Then we have used the Golang string.Join() function again, but this time, we have passed (,) Comma. So, command separated values will be returned, which is also a type of string.
So, if you want to get CSV values in Golang, then you can use the Go string.Join() method.
You can also try with functions:-
// abc.go
package main
type deck []string
func (cards deck) toString() string {
// converts slice to string
return strings.Join([]string(cards), ",")
}
//main.go
package main
import "fmt"
func main() {
cards := []string {"Trump", "In", "India", "On", "Feb 25"}
fmt.Println(cards.toString())
}

Case insensitive string replace in Go

Can NewReplacer.Replace do case insensitive string replacement?
r := strings.NewReplacer("html", "xml")
fmt.Println(r.Replace("This is <b>HTML</b>!"))
If not, what's the best way to do case insensitive string replace in Go?
You can use regular expressions for that:
re := regexp.MustCompile(`(?i)html`)
fmt.Println(re.ReplaceAllString("html HTML Html", "XML"))
Playground: http://play.golang.org/p/H0Gk6pbp2c.
It's worth noting that case is a thing that can be different depending on the language and locale. For example, the capital form of German letter "ß" is "SS". While this doesn't generally influence English texts, this is something to bear in mind when working with multi-lingual texts and programs that need to work them.
A generic solution would be as follows:
import (
"fmt"
"regexp"
)
type CaseInsensitiveReplacer struct {
toReplace *regexp.Regexp
replaceWith string
}
func NewCaseInsensitiveReplacer(toReplace, replaceWith string) *CaseInsensitiveReplacer {
return &CaseInsensitiveReplacer{
toReplace: regexp.MustCompile("(?i)" + toReplace),
replaceWith: replaceWith,
}
}
func (cir *CaseInsensitiveReplacer) Replace(str string) string {
return cir.toReplace.ReplaceAllString(str, cir.replaceWith)
}
And then used via:
r := NewCaseInsensitiveReplacer("html", "xml")
fmt.Println(r.Replace("This is <b>HTML</b>!"))
Here's a link to an example in the playground.
Based on the documentation it does not.
I am not sure about the best way, but you can do this with replace in regular expressions and make it case-insensitive with i flag

Resources