教学大纲
Java 程序
设计实验
报告 实验序号: 实验序号: 实 验 四 实验名称: 实验名称:
Java 字符串与常用类 班 学 姓 级: 计算机 091 号: 名:
教学大纲
实验四
(一)实验目的
Java 字符串与
常用类
(1)使学生初步掌握字符串类的使用方法。 (2)使学生初步掌握一些常用类的使用方法。 (二)实验内容 (1)以下代码可实现将一个文本文件的内容读出并存储到一个字符串变量中,在此代 码基础上编程实现以下字符串操作: a. 输入一个子串 s,查找 s 在文件中出现的位置,打印出所有的位置。 (indexof 方法) b. 输入开始位置 startpoint 和结束位置 endpoint,输出文件中相应位置的子串。 (substring 方法) c. 输入一个旧串 oldStr 和一个新串 newStr,将文件中所有 oldStr 子串用 newStr 代替,输出代替后的结果。 (replaceAll 方法) d. 使用 stringtokenizer 类实现分词,要求能将英文文本文件中所有的单词分解出 来,统计每个单词在文件中出现的次数,输出单词及出现次数。 附读文件代码:
import java.io.*; FileInputStream istream; File file=new File("c:\\1.txt"); byte[] b=new byte[(int)file.length()]; try{ istream=new FileInputStream(file); istream.read(b); } catch(IOException e) {} String str=new String(b); System.out.println(str);
源代码: import java.util.*; import java.io.*; public class Problem1 { public static void main(String[] args) { FileInputStream istream; File file=new File("d:\\1.txt"); byte[] b=new byte[(int)file.length()];
教学大纲 try{ istream=new FileInputStream(file); istream.read(b); } catch(IOException e){ } String str=new String(b); System.out.println(str); System.out.println("(a)、请输入一行子串:"); Scanner reader=new Scanner(System.in); String s1=reader.nextLine(); int i=0; while(str.indexOf(s1,i)!=-1){ System.out.println(str.indexOf(s1,i)+" "); i=str.indexOf(s1,i)+1; } System.out.println("(b)、请输入开始位置和结束位置:"); Scanner x=new Scanner(System.in); int b1=x.nextInt(); int b2=x.nextInt(); System.out.println(str.substring(a1,a2)); System.out.println("(c)、请输入一个旧串和一个新串:"); Scanner y=new Scanner(System.in); String oldstr=y.nextLine(); String newstr=y.nextLine(); System.out.println(str.replaceAll(oldstr,newstr)); System.out.println("(d)、"); StringTokenizer fenli=new StringTokenizer(str,",.?! "); int times[]=new int[100]; String words[]=new String[100]; int temp,i,j; for(i=0;i
教学大纲 words[0]=fenli.nextToken(); for(i=1;fenli.hasMoreTokens();i++){ temp=0; words[i]=fenli.nextToken(); for(j=0;j } } (2)编程输出用户从键盘中输入的字符串中
与模式[24680]A[13579]{2}匹配的子字符 串; 源代码: import java.util.regex.*; import java.util.Scanner; public class Pipei{ public static void main(String args[]){ Scanner reader=new Scanner(System.in); String s1=reader.nextLine(); Pattern p; Matcher m; p=Patternpile("[24680]A[13579]{2}"); m=p.matcher(s1); while(m.find()){
教学大纲 String str=m.group(); System.out.print("从"+m.start()+"到"+m.end()+"匹配的子字符串:"); System.out.println(str); } } } 结果:
(3) 编写程序, 输出某年某月的日历页, 通过 main()方法将参数年和月传递到程序中; 源程序: import java.util.*; imp