实验六

实验六   字符串

 

【目的】

掌握String类的常用方法

【内容】

   1.String类的常用方法。

²  实验要求:

编写一个Java应用程序,判断两个字符串是否相同,判断字符串的前缀、后缀是否和某个字符串相同,按字典顺序比较两个字符串的大小关系,检索字符串,创建字符串,将数字型字符串转换为数字,将字符串存放到数组中,用字符数组创建字符串。。

²  程序运行效果示例:

            程序运行效果如下图所示:

           

²  程序模板

StringExample.java

class StringExample

{   public static void main(String args[])

    {   String s1=new String("you are a student"),

               s2=new String("how are you");

        if(【代码1】) // 使用equals方法判断s1与s2是否相同

         {

            System.out.println("s1与s2相同");

         }

        else

         {

           System.out.println("s1与s2不相同"); 

         }

         String s3=new String("22030219851022024");

         if(【代码2】)   //判断s3的前缀是否是“220302”。

         {

             System.out.println("吉林省的身份证");

         }

         String s4=new String("你"),

              s5=new String("我");

         if(【代码3】)//按着字典序s4大于s5的表达式。

         {

             System.out.println("按字典序s4大于s5");

         }

         else

         {

             System.out.println("按字典序s4小于s5");

         }

         int position=0;

         String path="c:\\java\\jsp\\A.java";

         position=【代码5】 //获取path中最后出现目录分隔符号的位置

         System.out.println("c:\\java\\jsp\\A.java中最后出现\\的位置:"+position);

         String fileName=【代码6】//获取path中“A.java”子字符串。

         System.out.println("c:\\java\\jsp\\A.java中含有的文件名:"+fileName);

         String s6=new String("100"),

                s7=new String("123.678");

         int n1=【代码7】     //将s6转化成int型数据。

         double n2=【代码8】  //将s7转化成double型数据。

         double m=n1+n2;

         System.out.println(m);

         String s8=【代码9】 //String调用valuOf(int n)方法将m转化为字符串对象

         position=s8.indexOf(".");

         String temp=s8.substring(position+1);

         System.out.println("数字"+m+"有"+temp.length()+"位小数") ;

         String s9=new String("ABCDEF");

         char a[]=【代码10】   //将s8存放到数组a中。

         for(int i=a.length-1;i>=0;i--)

          {

             System.out.print(" "+a[i]);

          }

    }

}

²  实验后的练习:

1. 程序中的s6改写成

String s6=new String(“1a12b”);

运行时提示怎样的错误?

2. 请用数组a的前3个单元创建一个字符串并输出该串。

3. 请给出获取path中“jsp”子字符串的代码。

4. 在程序的适当位置增加如下代码,注意输出的结果。

String str1=new String(“ABCABC”),

     str2=null,

     str3=null,

     str4=null;

str2=str1.replaceAll(“A”,”First”);

str3=str2.replaceAll(“B”,”Second”);

str4=str3.replaceAll(“C”,”Third”);

System.out.println(str1);

System.out.println(str2);

System.out.println(str3);

System.out.println(str4);

5. 可以使用Long类中的下列static方法得到整数各种进制的字符串表示:

   Public static String toBinaryString(long i)

   Public static String toOctalString(long i)

Public static String toHexString(long i)

Public static String toString(long i,int p)

其中的toString(long i, int p)返回整数i的p进制表示。请在适当位置添加代码输出12345的二进制、八进制和十六进制表示。

6. 在适当位置添加代码,分别输出数字m的整数部分和小数部分。

posted @ 2014-10-11 16:09  课堂  阅读(1108)  评论(0编辑  收藏  举报