Functions for Strings in Java
In this tutorial, you will learn how to make better use of built-in functions for Strings in Java to program more quickly, effectively, and aesthetically.
Join the DZone community and get the full member experience.Join For Free
What Is a String?
Firstly, of course, we have to initialize our string. What is a string used for?
- You want to look at your string as a line, not as a mass of symbols.
- If you have a long text, you want to work with the words, not the letters.
- If you have lots of information, you need functions that solve questions as quickly as possible.
Initializing a String
Or with appropriate length:
String line = new String[any length];
Getting a Line From Console
Scanner in = new Scanner(System.in);
String line = in.nextLine();
Getting a Position
If you need the position of any symbol, use
It returns a numeric value (position) of a symbol (first if they are repeating) written in brackets.
int pos = line.indexOf('any symbol');
Remember, ' ' is for symbols, and " " is for String (mass of symbols).
When you get your position, you can cut your string.
For example, if you have
line="Hello-World" and you want to get
line="Hello World", you need a position of '-' and then you may cut it.
Here, in brackets (start position, end position); so you cut from 0 position to the position of '-'. Here, the position is 5. So
newline = line.substring(0,5);
Then add the "tail" of our line ("World").
newline += line.substring(6, line.length());
Length regulates the number of symbols in your line. So it can be used as the end position in the substring.
If we want to compare two strings, we use
equals(...). It returns a boolean variable, so the result can be true or false. It is mostly used with if statements.
Checking for emptiness is very important in case you don't want to catch mistakes. It returns a boolean variable, so the result can be only true or false. Oftentimes, we use
isEmpty(...) in if statements.
If you want to compare some parts (using patterns), rather than entire lines, use
matches(). Patterns are regular expressions. matches() return a boolean variable, so mostly used with if statements.
Further Reading: More Regular Expressions
Opinions expressed by DZone contributors are their own.