What is the easiest way to iterate through the characters of a string in Java

0 votes
Please help.
Jul 13, 2018 in Java by Akrati
• 3,170 points
467 views

2 answers to this question.

0 votes

The below code seems the easiest to me:

String str = "...abc...";

for (int i = 0; i < str.length(); i++)
{
    char c = str.charAt(i);        
}
answered Jul 13, 2018 by scarlett
• 1,270 points
0 votes

There are two approaches to this:

for(int i = 0, n = s.length() ; i < n ; i++) {
    char c = s.charAt(i); }

or

for(char c : s.toCharArray()) {
    // process c}

The second approach is more readable while the first one is more faster.

answered Aug 19, 2019 by Sirajul
• 58,990 points

Related Questions In Java

0 votes
1 answer

What is the simplest way to read JSON from a URL in java

Read json from url use url.openStream() and read contents ...READ MORE

answered Jun 13, 2018 in Java by samarth295
• 2,200 points
3,130 views
+1 vote
4 answers

What is a simple way to repeat a string in java?

There is already answer wriiten using StringBuilder ...READ MORE

answered Dec 16, 2020 in Java by Rajiv
• 8,880 points
18,599 views
0 votes
2 answers

In Java, what is the best way to determine the size of an object?

I happened to find a java class "jdk.nashorn.internal.ir.debug.ObjectSizeCalculator", ...READ MORE

answered Aug 19, 2019 in Java by Sirajul
• 58,990 points
3,758 views
0 votes
2 answers

What's the best way to check if a String represents an integer in Java?

You can also use regular expression. str.matches("-?\\d+"); It will ...READ MORE

answered Aug 9, 2018 in Java by Daisy
• 8,110 points
2,093 views
0 votes
1 answer

Iterate through a HashMap.

Iterate through the entrySet() like so: public static void printMap(Map ...READ MORE

answered Dec 22, 2020 in Java by Gitika
• 65,870 points
39 views
+5 votes
4 answers

How to execute a python file with few arguments in java?

You can use Java Runtime.exec() to run python script, ...READ MORE

answered Mar 27, 2018 in Java by DragonLord999
• 8,450 points

edited Nov 6, 2018 by Omkar 38,397 views
+1 vote
1 answer

How to handle drop downs using Selenium WebDriver in Java

First, find an XPath which will return ...READ MORE

answered Mar 27, 2018 in Selenium by nsv999
• 5,520 points
5,054 views
0 votes
1 answer

What are the differences between getText() and getAttribute() functions in Selenium WebDriver?

See, both are used to retrieve something ...READ MORE

answered Apr 5, 2018 in Selenium by nsv999
• 5,520 points
11,439 views
0 votes
1 answer

What is the use of assert keyword in java?

Java assertion feature allows the developer to ...READ MORE

answered Jun 28, 2018 in Java by scarlett
• 1,270 points
199 views
0 votes
1 answer

Why there is the need of getters and setters in java

In Java getters and setters are completely ...READ MORE

answered Jun 26, 2018 in Java by scarlett
• 1,270 points
1,139 views