문자열의 모든 문자에 for-each 루프를 어떻게 적용합니까?
그래서 문자열의 각 문자를 반복하고 싶습니다.
그래서 나는 생각했다.
for (char c : "xyz")
하지만 컴파일러 오류가 발생합니다.
MyClass.java:20: foreach not applicable to expression type
어떻게해야합니까?
대한-각 각에 가장 쉬운 방법 char
A의가 String
사용하는 것입니다 toCharArray()
:
for (char ch: "xyz".toCharArray()) {
}
이것은 for-each 구성의 간결성을 제공하지만 불행히도 String
(불변)는 char[]
(변경 가능) 을 생성하기 위해 방어 사본을 수행해야 하므로 비용이 약간 듭니다.
로부터 문서 :
[
toCharArray()
복귀] 새로 할당 된 문자 배열 이 문자열의 길이와 내용이 문자열로 표시하는 문자 시퀀스를 포함하도록 초기화된다.
배열에서 문자를 반복하는 더 자세한 방법이 CharacterIterator
있지만 (정규 for 루프 등), toCharArray()
각 비용 을 기꺼이 지불하려는 경우 가장 간결합니다.
String s = "xyz";
for(int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
}
toCharArray
String 클래스 의 () 메서드를 사용하여 String 객체를 char 배열로 변환해야합니다 .
String str = "xyz";
char arr[] = str.toCharArray(); // convert the String object to array of char
// iterate over the array using the for-each loop.
for(char c: arr){
System.out.println(c);
}
또 다른 유용한 솔루션은이 문자열을 문자열 배열로 사용할 수 있습니다.
for (String s : "xyz".split("")) {
System.out.println(s);
}
Java 8 에서는 다음과 같이 해결할 수 있습니다.
String str = "xyz";
str.chars().forEachOrdered(i -> System.out.print((char)i));
chars () 메소드 IntStream
는 doc 에서 언급 한대로를 반환합니다 :
이 순서로부터 char 값을 제로 확장하는 int의 스트림을 돌려줍니다. 대리 코드 포인트에 매핑되는 모든 문자는 해석되지 않은 상태로 전달됩니다. 스트림을 읽는 동안 시퀀스가 변경되면 결과가 정의되지 않습니다.
왜 사용 forEachOrdered
하지 forEach
않습니까?
의 동작이 forEach
명확하게 결정적되는 위치로서 forEachOrdered
수행이 스트림의 각 요소에 대한 액션, 스트림의 발생 순서 스트림 정의 발생 순서를 갖는 경우. 따라서 forEach
주문이 유지된다는 보장은 없습니다. 또한이 질문 을 확인하십시오 .
codePoints()
인쇄 에도 사용할 수 있습니다 . 자세한 내용 은이 답변 을 참조하십시오.
불행히도 Java는 String
구현 하지 않습니다 Iterable<Character>
. 이것은 쉽게 할 수 있습니다. 이 StringCharacterIterator
하지만도 구현하지 않습니다 Iterator
... 그래서 자신합니다
public class CharSequenceCharacterIterable implements Iterable<Character> {
private CharSequence cs;
public CharSequenceCharacterIterable(CharSequence cs) {
this.cs = cs;
}
@Override
public Iterator<Character> iterator() {
return new Iterator<Character>() {
private int index = 0;
@Override
public boolean hasNext() {
return index < cs.length();
}
@Override
public Character next() {
return cs.charAt(index++);
}
};
}
}
이제 (어쩌면) 쉽게 실행할 수 있습니다 for (char c : new CharSequenceCharacterIterable("xyz"))
...
If you use Java 8, you can use chars()
on a String
to get a Stream
of characters, but you will need to cast the int
back to a char
as chars()
returns an IntStream
.
"xyz".chars().forEach(i -> System.out.print((char)i));
If you use Java 8 with Eclipse Collections, you can use the CharAdapter
class forEach
method with a lambda or method reference to iterate over all of the characters in a String
.
CharAdapter.adapt("xyz").forEach(c -> System.out.print(c));
This particular example could also use a method reference.
CharAdapter.adapt("xyz").forEach(System.out::print)
Note: I am a committer for Eclipse Collections.
You can also use a lambda in this case.
String s = "xyz";
IntStream.range(0, s.length()).forEach(i -> {
char c = s.charAt(i);
});
For Travers an String you can also use charAt()
with the string.
like :
String str = "xyz"; // given String
char st = str.charAt(0); // for example we take 0 index element
System.out.println(st); // print the char at 0 index
charAt()
is method of string handling in java which help to Travers the string for specific character.
'IT story' 카테고리의 다른 글
열을 변경하고 기본값을 변경하는 방법은 무엇입니까? (0) | 2020.05.25 |
---|---|
iTerm이 다른 OS와 동일한 방식으로 '메타 키'를 번역하도록 만들기 (0) | 2020.05.25 |
Excel : 문자열에서 마지막 문자 / 문자열 일치 (0) | 2020.05.25 |
DataContract 및 DataMember 특성을 언제 사용합니까? (0) | 2020.05.25 |
파이썬 덤프 dict to json 파일 (0) | 2020.05.25 |