Merge pull request #15073 from Neetika23/stringIterationCode
String iteration code
This commit is contained in:
commit
47856fa103
|
@ -0,0 +1,42 @@
|
|||
package com.baeldung.stringIterator;
|
||||
|
||||
import java.text.*;
|
||||
import java.util.*;
|
||||
|
||||
public class StringIterator {
|
||||
|
||||
public static String javaCharArray(String str){
|
||||
StringBuilder result = new StringBuilder();
|
||||
for (char c : str.toCharArray()) {
|
||||
result.append(c);
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
public static String javaforLoop(String str) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
for (int i = 0; i < str.length(); i++) {
|
||||
char c = str.charAt(i);
|
||||
result.append(c);
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
public static String java8forEach(String str){
|
||||
StringBuilder result = new StringBuilder();
|
||||
str.chars().forEach(name -> {
|
||||
result.append((char) name);
|
||||
});
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
public static String javaCharacterIterator(String str){
|
||||
StringBuilder result = new StringBuilder();
|
||||
CharacterIterator it = new StringCharacterIterator(str);
|
||||
while (it.current() != CharacterIterator.DONE) {
|
||||
result.append(it.current());
|
||||
it.next();
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
package com.baeldung.stringIterator;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
public class StringIteratorTest {
|
||||
|
||||
@Test
|
||||
public void whenUseCharArrayMethod_thenIterate() {
|
||||
String input = "Hello, Baeldung!";
|
||||
String expectedOutput = "Hello, Baeldung!";
|
||||
String result = StringIterator.javaCharArray(input);
|
||||
assertEquals(expectedOutput, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUseJavaForLoop_thenIterate() {
|
||||
String input = "Hello, Baeldung!";
|
||||
String expectedOutput = "Hello, Baeldung!";
|
||||
String result = StringIterator.javaForLoop(input);
|
||||
assertEquals(expectedOutput, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUseForEachMethod_thenIterate() {
|
||||
String input = "Hello, Baeldung!";
|
||||
String expectedOutput = "Hello, Baeldung!";
|
||||
String result = StringIterator.java8ForEach(input);
|
||||
assertEquals(expectedOutput, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUseCharacterIterator_thenIterate() {
|
||||
String input = "Hello, Baeldung!";
|
||||
String expectedOutput = "Hello, Baeldung!";
|
||||
String result = StringIterator.javaCharacterIterator(input);
|
||||
assertEquals(expectedOutput, result);
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue