DEV Community

Yuri Filatov
Yuri Filatov

Posted on • Updated on • Originally published at andersenlab.com

Java: Helpful tips for usage of string

I don't think there is need to explain the meaning of string. We can simply name it as a line and I would say that it is much better to use string than char (symbols) as there are more interesting tools and functions for it.

Let's start!

*1. Devide string

Indexof() brings the numeric value as it finds the first position of entered symbol (or returns -1 if not found). So it can be used together with substring(), which cuts, to devide string and to keep the result also in string. Example:

while (s.indexOf(' ') != -1) { int k = s.indexOf(' '); s_devided+=s.substring(0,k); s = s.substring(k + 1, s.length()); }

P.S. length() returns a numeric value (how much symbols does your line have)

*2. Devide string Pro

What if we devide string using some pattern? For example we want to spit the words. So we need a mas to keep all the words together.

String[] mas = new string [any length];

Then we have to use split() to delete all " "
Example:

String pattern = " ";
mas = line.split(pattern);

If our line="hello to all programmists", then we have mas[0]="Hello", mas[1]="to" and so on.

*3. Making copies carefully and correctly

Use System.arraycopy()
How to use it?

System.arraycopy(start mas1, first index mas1, result mas2, first index mas2, length);

*4. Num check

If you want to convert your string into a numeric value, you can catch a mistake if it is not a num, so you programm will work incorrectly. Check with the function if it is a num and only then convert.

public static boolean isNumeric(String strNum) {
try {
long d = Long.parseLong(strNum);
} catch (NumberFormatException | NullPointerException nfe) {
return false;
}
return true;
}

Other tools are simple for me in usage and don't need any explanation. If you have any questions, write me anytime.

Good luck in your job!

Top comments (0)