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 FreeWhat 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
String line;
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 indexOf(...)
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).
Cut
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.
Functions
substring(...)
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()
Length regulates the number of symbols in your line. So it can be used as the end position in the substring.
Equals(...)
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.
if (line.equals(newline)==true) {
System.out.println("Your lines are equal");
}
isEmpty(...)
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.
xxxxxxxxxx
if (line.isEmpty()) {
System.out.println("Your line is empty");
}
matches()
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.
xxxxxxxxxx
if (line.matches ("\\d{3}") {
System.out.println("Your line contains 3 numbers");
}
Further Reading: More Regular Expressions
Opinions expressed by DZone contributors are their own.
Comments