Last Updated: May 17, 2021
·
22
· Yuri Filatov

Functions for string in java

I've already made an article for some helpful tips, but I think there is a need to discuss all functions too. Shortly but understandable.
String

Firstly, of course, we have to initialize our string. What string is used for?

  • You want to look at your string as a line, not a mass of symbols.
  • You have a long text, so you work not with the letters, but with the words
  • If you have big information, you need functions that solve questions as quickly as possible.

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();

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.

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, " " is for String (mass of symbols).

Cut

So when you get your position, you can cut your string.

For example, line="Hello-World" and you want to get line="Hello World", so you need a position of '-' and then cut it;

We use 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() is the amount of symbols in your line. So it can be used as the end position in 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.
Mostly used with if

if (line.equals(newline)==true)
{
System.out.println("Your lines are equal");
}

Empty

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. We use isEmpty(...)

if (line.isEmpty())

{

System.out.println("Your line is empty");

}

Matches

If you want to compare not the whole lines, but some parts (using pattern), use matches()

It returns a boolean variable, so mostly used with if

Pattern = regular expression

if (line.matches ("\\d{3}")
{
System.out.println("Your line contains 3 numbers");
}

Table with more information for regex: regular expressions

I hope, for one article it is enough written. If you want more, react on this article with likes or so on.

Good luck in your job!