实验三 String类的应用

实验目的

掌握类String类的使用;

七大方法d'd

学会使用JDK帮助文档;

实验内容

1.已知字符串:"this is a test of java".按要求执行以下操作:(要求源代码、结果截图。)
1.统计该字符串中字母s出现的次数。

代码:

package test;
public class test {	   
    public static void main(String [] args){ 
    	int sum = 0;
    	String str = "this is test of java";
    	char c[] = str.toCharArray();
    	for(int i = 0;i<c.length;i++) {
    		if(c[i] == 's') {
    			sum++;
    		}
    	}
    	System.out.println(sum);
    }
}
2.统计该字符串中子串“is”出现的次数。

代码:

package test;
public class test {	   
    public static void main(String [] args){ 
    	int sum = 0;
    	String str = "this is test of java";
    	char c[] = str.toCharArray();
    	for(int i = 0;i<c.length;i++) {
    		if(c[i] == 'i'&&c[i+1] == 's') {
    			sum++;
    		}
    	}
    	System.out.println(sum);
    }
}
3.统计该字符串中单词“is”出现的次数。

代码:

package test;
public class test {	   
    public static void main(String [] args){ 
    	int sum = 0;
    	String str = "this is test of java";
    	char c[] = str.toCharArray();
    	for(int i = 0;i<c.length;i++) {
    		if(c[i] == ' '&&c[i+1] == 'i') {
    			sum++;
    		}
    	}
    	System.out.println(sum);
    }
}
4.实现该字符串的倒序输出。

代码:

package test;

public class ban {
    public static void main(String[] args) {
        String str = "this is test of java";
        
        for (int j = str.length()-1; j>=0; j--) {
            char a = str.charAt(j);
            System.out.print(a);
       }
    
    }
}

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

代码:

package test;

public class test {
    public static void main(String[] args) {
	    
        String str = "This is a secret";
        char[] c= str.toCharArray();
        System.out.println("请输出加密后的字符串:");
        for(char x:c) {  //对字符串进行加密
        	    System.out.print((char) (x+3));
        }
        
    }
}

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

代码:

package test;

public class test {
    public static void main(String[] args) {
    	
        String str = "ddejidsEFALDFfnef23573ed";
        
        System.out.println("请输出大写字母:");
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') {
                System.out.print(str.charAt(i));
            }
        }
        
        System.out.println();
        System.out.println("请输出小写字母:");
            for (int j= 0; j < str.length(); j++) {
                if (str.charAt(j) >= 'a' && str.charAt(j) <= 'z') {
                    System.out.print(str.charAt(j));
                }
            }
            
       System.out.println();
       System.out.println("请输出其他字符:");
       for (int k= 0; k < str.length(); k++){
	       if(str.charAt(k)<'A'||str.charAt(k)>'z')
		       System.out.print(str.charAt(k));
            }
    }
}

截图:

 posted on 2019-09-26 23:23  怪她  阅读(153)  评论(0编辑  收藏  举报