Blockchain, Cryptocurrency & Smart Contracts
+34 518 880131

Blog

Official SigloTech Blog

  • Welcome, Guest!

By browsing this website you are agreeing to our use of cookies.

Posts tagged with “go”

String Functions in Go – Part 1

Go is a powerful programming language in the best tradition of C. However, Go tries to eliminate some of C’s shortcomings. If you programmed Go, you probably like the brevity and safety. Yes, safety and comfort come at a cost of performance but Go is still insanely fast language.

One of the areas where Go is dramatically better than C is working with strings. The strings package is Go’s powerhouse for working with strings. The package contains many string functions and makes string manipulation a breathe. Though, there are some caveats and it’s very important to know what the strings package delivers.

The first thing that you need to remember is that some of Go’s string functions are CaSe SeNsItIvE, while others are not. I will clearly indicate this along with each function below.

When working with strings, we face two group of tasks. The first group is querying and checking (e.g. if strings are equal, if one string contains another, etc). The second group is actual manipulation of strings (e.g. removing characters from a string, replacing something in a string, etc). In this part I will focus on the first group. The second group will be addressed in a separate post. Let’s get started.

How to Compare Strings

One of the most common tasks when working with strings is string comparison. In Go you can do this either by using the strings.Compare function or by using the built-in operators: ==, <, >. String comparison is CaSe SeNsItIvE!

Function:

func Compare(a, b string) int

Let’s have a look at an example:

package main

import (
	"fmt"
	"strings"
)

func main() {

	fmt.Println(strings.Compare("MAGIC", "magic")) // MAGIC is less than magic - CaSe SeNsItIvE
	fmt.Println(strings.Compare("MAGIC", "MAGIC")) // MAGIC and MAGIC are equal

	fmt.Println(strings.Compare("", ""))  // empty strings are equal
	fmt.Println(strings.Compare("", " ")) // empty string is less than any other string

	fmt.Println("MAGIC" == "magic") // prints false as the strings are not equal
	fmt.Println("MAGIC" < "magic")  // prints true as MAGIC is less then magic

}

Do you want to test how well you grasped string comparison? Without using Go, guess what the following statement would print:

fmt.Println(("MAGIC" < "magic") == (strings.Compare("MAGIC", "magic") == -1))

How to Check if One String Contains Another

Another common task is checking if one string contains another string. For this task, we can use the strings.Contains function. You feed in two strings and get a boolean result. This function is also CaSe SeNsItIvE! Another thing to note is that empty string always contains empty string.

Function:

func Contains(s, substr string) bool

Let’s have a look at an example:

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.Contains("It's a kind of magic", "magic")) // prints true
	fmt.Println(strings.Contains("It's a kind of magic", "MAGIC")) // prints false - CaSe SeNsItIvE
	fmt.Println(strings.Contains("", ""))                          // prints true - empty string contains empty string
}

How to Check if Characters are Present in a String

Sometimes you need to check if certain characters are present in a given string. You could use several strings.Contains function calls when you have more than two characters but there’s a better way in Go – the strings.ContainsAny function.

Function syntax:

func ContainsAny(s, chars string) bool

Let’s have a look at the example:

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.ContainsAny("magic", "m"))   // prints true - m is in magic
	fmt.Println(strings.ContainsAny("magic", "M"))   // prints false - M is not in magic
	fmt.Println(strings.ContainsAny("magic", "m a")) // prints true - both m and a are in magic
	fmt.Println(strings.ContainsAny("magic", "m z")) // prints true - z is not in magic, but m is.
	fmt.Println(strings.ContainsAny("magic", "p z")) // prints false - neither p nor z are present in magic
}

How to Find a Position of a Sub-string in another String

Use strings.Index function to find a position of a sub-string in a string. The function returns -1 if the string does not contain sub-string or a value of zero or more. Zero means the beginning of the string. Like the previous functions, strings.Index function is also CaSe SeNsItIvE!

Function syntax:

func Index(s, substr string) int

Let’s look at the example:

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.Index("magic", "gi")) // prints 2 - gi occurs at index 2
	fmt.Println(strings.Index("magic", "GI")) // prints -1 - GI because Index function is CaSe SeNsItIvE
	fmt.Println(strings.Index("magic", "me")) // prints -1 - me does not occur in magic

}

How to Find Positions of Characters in a String

Like the strings.Contains function has a strings.ContainAny cousin, so does strings.Index has strings.IndexAny function. Though, it’s a little bit more subtle. The example below will show them. This function is also CaSe SeNsItIvE!

Function syntax:

func IndexAny(s, chars string) int

Let’s look at the example:

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.IndexAny("magic", "a c")) // prints 1 - a's position is returned
	fmt.Println(strings.IndexAny("magic", "j c")) // prints 4 - c's position is returned
	fmt.Println(strings.IndexAny("magic", "A C")) // prints -1 - as neither A nor C is present in magic

}

One thing to keep in mind is that strings.Index and strings.IndexAny functions return the index of the first occurrence of a sub-string or chars. It is also possible to find the last occurance of a sub-string or char by using the strings.LastIndex and strings.LastIndexAny functions.

Funtion syntax:

func LastIndex(s, substr string) int
func LastIndexAny(s, chars string) int

Let’s look at a combined example of Index, IndexAny, LastIndex and LastIndexAny functions.

age main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.Index("magic tricks", "ic"))     // prints 3 - ic's first position
	fmt.Println(strings.LastIndex("magic tricks", "ic")) // prints 8 - ic's last position

	fmt.Println(strings.IndexAny("magic tricks", "a c"))     // prints 1 - a's first position
	fmt.Println(strings.LastIndexAny("magic tricks", "a c")) // prints 9 - c's last position

}

How to Find Out if a String Begins or Ends with a Certain Sub-string

Go’s strings package contains two more useful functions, strings.HasPrefix and strings.HasSuffix. Use these functions to test if a string has certain beginning or ending. Like the other string functions, these two are also CaSe SeNsItIvE!

Function syntax:

func HasPrefix(s, prefix string) bool
func HasSuffix(s, suffix string) bool

Let’s look at the examples:

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.HasPrefix("magic", "ma")) // prints true - magic starts with ma
	fmt.Println(strings.HasPrefix("magic", "MA")) // prints false - magic does not starts with MA
	fmt.Println(strings.HasSuffix("magic", "ic")) // prints true - magic ends with ic
	fmt.Println(strings.HasSuffix("magic", "IC")) // prints false - magic does not ends with IC
}

I hope you found the above overview and examples useful. There are some other string functions in the strings package, but they are used less frequently. At least, I have described all high-frequency string functions. In the next post I will write how to do some interesting things with our strings. Stay tuned and happy programming!

Tags: go programming string-functions

Top Five Programming Languages To Learn

I often get asked by aspiring programmers (and more often by their parents) what programming languages they should learn. You may think that learning programming languages is a matter of taste. However, that’s very far from being true. I will bring just two arguments.

First, if you want to become a professional programmer and earn living by programming, you have to learn at least one programming language that is in great demand. Ideally, you should know two such languages.

Second, there are languages that are used for specific purposes. For example, even if you bring gazillion reasons why C++ is better than Javascript, one thing is undeniable. If you want to create front-end code that runs in browser you need to use Javascript.

In this article I will list top five languages that I think you should know. Moreover, I will provide rationale behind each choice. The order of the list is not very important.

C/C++

C has been around from early 1970s. It’s one of the most minimalist programming languages. If you do it right, code written in C is blazing-fast. This should not come as a surprise. C is very close to hardware, does not have checks and gives you so much freedom. Programs written in C will run everywhere from supercomputers to micro-controllers. For decades all attempts to replace C with other programming languages have failed. In early 2000s it was predicted that C would die. As far as C’s health is concerned it’s doing really well. C will be around for many years.

The same can be said about C’s big brother C++. C++ takes C to different heights. It’s a powerful, industrial-grade language. At lower levels, almost every software (operating systems, game engines, databases, even other programming languages, etc) are implemented in C or C++. Hence, if you want to have guaranteed and well paid job learn C/C++.

Personally I do not do much C++ programming but use C actively from hobby projects to commercial projects especially for IoT and robotics.

C# or Java

I’ve been programming C# since 2003, yeah almost 15 years. C# and Java are practically de-facto standards for enterprise programming. There are many reasons for this but the main reason is that both C# and Java are Internet/web oriented. At the same time, they are universal, support many programming paradigms and allow programming of practically everything. At the same time, they have good cross-platform capabilities (especially Java). Write once, run everywhere is indeed a great selling point for these languages. At the same time, both C# and Java developers are well paid and in constant demand.

Javascript or Typescript

Javascript is the world’s most popular programming (scripting) language. With the advent of server side Javascipt (yeah Node.js as you’ve probably heard) it has become truly ubiquitous. I have a love/hate relationship with Javascript because of its several idiosyncrasies. Though, it’s undeniable that if you learn Javascript you can do pretty much everything. If you plan to learn only one programming language, learn Javascript. You will be able to program everything from server-side to front-end and mobile. Though, I would recommend learning Typescript. Not only is Typescript more elegant and closer to a true programming language but it can also transpile into Javascript.

Python

Python is a cool scripting language. Python has very decent frameworks for web and fantastic support for machine learning. As machine learning has become a hot topic, so Python’s popularity is growing fast.

Go or Rust

Go or (Golang how it’s sometimes called) is a relatively new language created at Google. Go is a compiled, statically typed language. Go combines simplicity of C while providing memory safety and garbage collection. Go is much faster than C# and Java but not as fast as C. Though, where Go really shines is concurrency. I have not seen any other language where writing concurrent code is either as simple or pleasant as writing in Go. Go has a very decent standard library implementing all kinds of functionalities. At the same time Go has grown in popularity. Don’t like Go? Then you may look into Rust. It’s a system programming language from Mozilla foundation. Rust is also a statically typed and compiled language and you can write safe code that also runs fast.

Functional and Exotic Languages

I know the title of the post says top five languages. But I find it very useful to learn at least one functional and one relatively exotic language. For functional languages you may learn Haskel or F#. If you are in math then you will find Haskel really cool.

Final Thoughts

Of course there are hundreds of programming languages out there. Not all of them are popular. Many have died. Yet, there are many popular languages that I have not listed. For example PHP. I program in PHP from time to time. Though if you know C# or Java or Python then PHP becomes really redundant. Don’t want to learn Python? Then you may replace it with PHP.

What about Perl? Perl is an excellent language and as a matter of fact I started web programming in Perl. Perl is also out of competition when it comes to text processing and Regular Expressions. What about Prolog, Lisp, Erlang, Ada? They are fantastic languages but of course they are not mainstream. Maybe your dream is to work for defense and aeronautics? Then learning Ada is a really nice idea. Well you get the point.

Finally, I would say that try as many programming languages as you can and then stick to those you really love. You will be spending days, months and years expressing yourself in languages of your choice.

Tags: c c go java javascript php programming-languages python rust typescript
About SigloTech

SigloTech is a software development and consulting company with a primary focus on Blockchain, Cryptocurrency and Smart Contracts.

Contact Details
Subscribe

Your privacy is our top priority!

©2018 SigloTech. All rights reserved.