JAVA实验报告三

Java实验报告

完成时间 2021.10.15

实验三String类的应用

一、实验目的

(1)掌握类String类的使用;
(2)学会使用JDK帮助文档;

二、实验内容

1.已知字符串:"thisisatestofjava".按要求执行以下操作:(要求源代码、结果截图。)
1统计该字符串中字母s出现的次数。
2统计该字符串中子串“is”出现的次数。
3统计该字符串中单词“is”出现的次数。
4实现该字符串的倒序输出。

实验源码:

package test3;
public class One {
public static void main(String[] args) {

        // TODO Auto-generated method stub

        int count=0;

        String s="this is a test of java";

        System.out.println((","+s+",").split("s").length-1);

        //方法一:split函数对字符串s在"s"位置进行拆分,然后通过.length得到拆分后的字符串的个数,减1得到"s"出现的次数

        char c[]=s.toCharArray();

        for(char e:c){

            if(e=='s'){

                count++;

            }

        }

        //方法二:用toCharArray函数将字符串s变成字符数组,用for each循环对字符数组进行遍历,判断并计数

        System.out.println((","+s+",").split("is").length-1); //同上方法一

        System.out.println((","+s+",").split(" is ").length-1); //同上

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

            System.out.print(c[i]);

        }

        //利用字符数组下标递减输出

        StringBuffer buffer = new StringBuffer(s);

        System.out.println("
"+buffer.reverse());

        //定义成一个StringBuffer类,用StringBuffer类中的reverse()方法直接倒序字符串。

}

}

实验结果:

2.请编写一个程序,使用下述算法加密或解密用户输入的英文字串。要求源代码、结果截图。

实验源码:

package test3;

import java.util.Scanner;

public class Two {

public static void main(String[] args) {
    @SuppressWarnings("resource")
    Scanner s = new Scanner(System.in);
    System.out.println("输入字符串:");
    String r = s.nextLine();
    char t[] = new char[r.length()];
    t=r.toCharArray();
    int i;
    for (i=0;i<t.length;i++) {
        t[i]=(char)(t[i]+3);
    }
    String c=" ";
    for (i=0;i<r.length();i++) {
        c=c+t[i];
    }
    System.out.println("改变后的字符串:"+c);
}

}
实验结果:

3.已知字符串“ddejidsEFALDFfnef23573ed”。输出字符串里的大写字母数,小写英文字母数,非英文字母数。

实验源码:

三、实验过程(请自己调整格式)
package test3;

public class Three {
public static void main(String[] args) {

	int ABC = 0, abc = 0, other = 0;

	String s = "ddejidsEFALDFfnef2357 3ed";

	char c[] = s.toCharArray();

	for (char e : c) {

		if (e >= 'A' && e <= 'Z') {

			ABC++;

		}

		else if (e >= 'a' && e <= 'z') {

			abc++;

		}

		else {

			if (e != ' ') {

				other++;

			}

		}

	}

	System.out.print("大写字母数:" + ABC + "
小写字母数:" + abc + "
非英文字母数:" + other);

}

}

实验结果:

原文地址:https://www.cnblogs.com/yuanweimin/p/15412582.html