2014-11-17 4 views
0

저는 Java를 처음 접했고 빠른 질문이있었습니다.Java에서 다른 배열의 일부 복사하기

내가 만든 studentInfo [0]이라는 배열이 있습니다. String studentInfo[] = line.split(","); 첫 번째 인덱스에서 다른 배열을 만들고 싶습니다.

다른 말로하면."a, b, c, d,
a1, b1, c1, d1, a2, b2, d2, c2 등 ..."다른 배열이 필요합니다. 그것은 다른 배열의 모든 "a"를 취합니다. 예 : "a, a1, a2 etc ..."

어떻게하면됩니까?

시도해 보았습니다. System.arraycopy(studentInfo, 0, array, 0, studentInfo.length);하지만 첫 번째 색인을 제공하지 않기 때문에 작동하지 않는 것 같습니다.

FYI 내 코드는 while 회 돌이를 사용하여 줄 바꿈을 할 때마다 반복됩니다. 아래 참조 :

while ((line = reader.readLine()) != null) { 
      String studentInfo[] = line.split(","); 
      String array[] = new String[0]; 
     } 

고마워요!

+2

처럼 보인다 - 그것은 무엇을하고 있습니까? 그게 무슨 소리 야? "doesnt는 일하는 것처럼 보인다"doesnt는 우리가 문제를 이해하는 것을 돕는다. 어떻게 작동하지 않습니까? "* 내 코드는 while 회 돌이 때마다 새로운 회선을 lo 때마다 반복됩니다. *"- 아마이 코드를 보여 주셔야합니다. –

답변

1

내가 좋아하는 뭔가를 할 것이라고합니다.

String[] studentInfoA = new String[50] //You can put the size you want. 

    for(int i=0; i<studentInfo.length-1; i++){ 
     if(studentInfo[i].substring(0,1).equals("a")){ 
      studentInfoA[i]=studentInfo[i]; 
     } 
    } 

내가 더 나은 Vimsha의 답변을 추천 할 것입니다하지만 당신은 학습 때문에 난 당신이 컬렉션과 같은 투쟁, 또는 적어도 내가 제대로 배열과 루프에 대해 모르고을 사용하려면 wouldnt가 만들고 싶어 didnt한다. 자바 1.8에서

1

,이 배열을

studentInfo = ["a","b","c","d","a1","b1","c1","d1", "a2","b2","d2","c2"] 

가정하면

studentInfoWithA = ["a", "a1", "a2"] 

같은 다른 배열이 다음

String studentInfo[] = new String[] { "a", "b", "c", "d", "a1", "b1", "c1", "d1", "a2", "b2", "d2", "c2" }; 

    List<String> newList = new ArrayList<String>(); 
    for (String info : studentInfo) { 
     if (info.startsWith("a")) { 
      newList.add(info); 
     } 
    } 

    String[] studentInfoWithA = newList.toArray(new String[0]); 
0

는 필터링 "* 그러나 작동하지 않는 것 *"

String[] result = Arrays.stream(new String[] { "a","b","c","d","a1","b1","c1","d1", "a2","b2","d2","c2" }) 
    .filter(e -> e.startsWith("a")) 
    .toArray(String[]::new);