문자열 분리에 사용
String 문자열="red,magenta,gray,pink,yellow";
String 객체의 split을 이용한 분리
String 배열명[]=문자열.split(분리기준);
문자열 분리에 사용
StringTokeneizer 객체를 이용한 분리
StringTokenizer 변수=new StringTokenizer(문자열명, 분리구분점);
while(변수.hasMoreTokens()) ->true가 있을때까지//다음토큰이 있으면 true,없으면 false
System.out.println(변수.nextToken()); -> false 나오기 전까지 다음토큰 계속 얻기
public class StringToken_07 {
public static void main(String[] args) {
//문자열을 특정문자로 분리하는 방법들
String str="red,magenta,gray,pink,yellow";
System.out.println("String 객체의 split을 이용한 분리");
String arrColors[]=str.split(",");
System.out.println("총 "+arrColors.length+"개");
for(int i=0;i<arrColors.length;i++)
{
System.out.println(i+": "+arrColors[i]);
}
System.out.println("StringTokeneizer 객체를 이용한 분리");
StringTokenizer st=new StringTokenizer(str, ","); //(String, 분리구분점)
System.out.println("총 토큰수: "+st.countTokens());
while(st.hasMoreTokens()) //->true가 있을때까지//다음토큰이 있으면 true,없으면 false
{
System.out.println(st.nextToken()); //다음토큰 계속 얻기//false 나오기 전까지
}
}
}
빈 문자열에 넣어주면 더 쉽게 대입 가능
public class FileToken_08 {
public static void movieRead() {
String fileName="/Users/sunghyunchoi/Desktop/sist0616/file/movie.txt";
FileReader fr=null;
BufferedReader br=null;
try {
fr=new FileReader(fileName);
br=new BufferedReader(fr);
System.out.println("***영화배우 오픈***");
System.out.println("배우명\t대표영화\t나이");
System.out.println("--------------------------");
while(true)
{
String s=br.readLine();
//종료
if(s==null)
break;
/*
//split분리
String data[]=s.split(",");
//배열개수만큼 반복해서 출력
System.out.println(data[0]+"\t"+data[1]+"\t"+data[2]);
*/
//Tokneizer 분리
StringTokenizer st=new StringTokenizer(s, ",");
System.out.println(st.nextToken()+"\t"+st.nextToken()+"\t"+st.nextToken());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
}finally {
try {
br.close();
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
movieRead();
}
}
public class QuizTokenFile_09 {
public static void fruitRead(){
/*
***과일목록***
상품 수량 단가 총금액
----------------------------------
바나나 10 5000 50000
*/
String fileName="/Users/sunghyunchoi/Desktop/sist0616/file/fruit.txt";
FileReader fr=null;
BufferedReader br = null;
try {
fr=new FileReader(fileName);
br=new BufferedReader(fr);
System.out.println("\t***과일목록***");
System.out.println("상품\t수량\t단가\t총금액");
System.out.println("----------------------------");
while(true)
{
String s=br.readLine();
if(s==null)
break;
String arr[]=s.split(",");
System.out.println(arr[0]+"\t"+arr[1]+"개"+"\t"+arr[2]+"원"
+"\t"+(Integer.parseInt(arr[1])*
Integer.parseInt(arr[2]))+"원");
/*
StringTokenizer ar=new StringTokenizer(s, ",");
//선생님 풀이
String sang=ar.nextToken();
int su=Integer.parseInt(ar.nextToken());
int dan=Integer.parseInt(ar.nextToken());
int total=su*dan;
System.out.println(sang+"\t"+su+"개"+"\t"+dan+"원"+"\t"+total+"원");
*/
}
}catch (IOException e) {
}
finally {
try {
br.close();
fr.close();
} catch (Exception e2) {
}
}
}
public static void main(String[] args) {
fruitRead();
}
}