DEV Community

Yuri Filatov
Yuri Filatov

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

3 1

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!

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay