Update StringIterator.java

This commit is contained in:
Neetika23 2023-10-26 23:57:27 +05:30 committed by GitHub
parent 0fa77ed809
commit 7aeb97fcdf
1 changed files with 25 additions and 19 deletions

View File

@ -6,48 +6,54 @@ import java.util.*;
public class StringIterator { public class StringIterator {
public static void main(String[] args) { public static void main(String[] args) {
String str = "Hello, Baeldung!"; String str = "Hello, Baeldung!";
javaforLoop(str); System.out.println(javaforLoop(str));
System.out.println(); System.out.println(java8forEach(str));
java8forEach(str); System.out.println(javaCharArray(str));
System.out.println(); System.out.println(javaRegexExp(str));
javaCharArray(str); System.out.println(javaCharacterIterator(str));
System.out.println();
javaRegexExp(str);
System.out.println();
javaCharacterIterator(str);
} }
public static void javaCharArray(String str){ public static String javaCharArray(String str){
StringBuilder result = new StringBuilder();
for (char c : str.toCharArray()) { for (char c : str.toCharArray()) {
System.out.print(c); result.append(c);
} }
return result.toString();
} }
public static void javaforLoop(String str) { public static String javaforLoop(String str) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < str.length(); i++) { for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i); char c = str.charAt(i);
System.out.print(c); result.append(c);
} }
return result.toString();
} }
public static void java8forEach(String str){ public static String java8forEach(String str){
StringBuilder result = new StringBuilder();
str.chars().forEach(name -> { str.chars().forEach(name -> {
System.out.print((char) name); result.append((char) name);
}); });
return result.toString();
} }
public static void javaRegexExp(String str){ public static String javaRegexExp(String str){
StringBuilder result = new StringBuilder();
String[] characters = str.split(""); String[] characters = str.split("");
for (String c : characters) { for (String c : characters) {
System.out.print(c); result.append(c);
} }
return result.toString();
} }
public static void javaCharacterIterator(String str){ public static String javaCharacterIterator(String str){
StringBuilder result = new StringBuilder();
CharacterIterator it = new StringCharacterIterator(str); CharacterIterator it = new StringCharacterIterator(str);
while (it.current() != CharacterIterator.DONE) { while (it.current() != CharacterIterator.DONE) {
System.out.print(it.current()); result.append(it.current());
it.next(); it.next();
} }
return result.toString();
} }
} }