String课堂作业
一、字串加密:
(1)程序设计思路:先输入一个String类型的字符串,然后将其转化为char型,利用数组输出其加密后的结果。
(2)程序流程图:
(3)源代码:
package zichuan;
import javax.swing.*;
public class Mima {
public static void main(String[] args){
String m; //定义一个字符串
m=JOptionPane.showInputDialog("请输入字符串:");
char[] ch=m.toCharArray(); //将字符串转化为char型
for(int i=0;i<m.length();i++){
if(ch[i]=='X'||ch[i]=='Y'||ch[i]=='Z'){
ch[i]=(char)(ch[i]-23);
} //最后三个字符的输出
else{
ch[i]=(char)(ch[i]+3);
} //其他字符串的输出
}
JOptionPane.showMessageDialog(null, "输出加密后的字符串"
+String.valueOf(ch)); //最终结果的输出
}
}
(4)结果截图:
二、动手动脑:
实现代码:
public class StringEquals {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String s1=new String("Hello");
String s2=new String("Hello");
System.out.println(s1==s2);
System.out.println(s1.equals(s2));
String s3="Hello";
String s4="Hello";
System.out.println(s3==s4);
System.out.println(s3.equals(s4));
}
}
结果截图:
实现方法:使用equals()或equalsIgnoreCase()方法比较两字串内容
是否相同,使用==比较两字串变量是否引用同一字串对象。
三、String类使用说明整理:
Length():获取字串长度
charAt():获取指定位置的字符
getChars():获取从指定位置起的子串复制到字符数组中(它有四个参数,1.被拷贝字符在字串中的起始位置。2.被拷贝的最后一个字符在字串中的下标再加1。3.目标字符数组。4.拷贝的字符放在字符数组中的起始下标)
replace():子串替换
toUpperCase()、 toLowerCase():大小写转换
trim():去除头尾空格:
toCharArray():将字符串对象转换为字符数组
代码://StringMisc.java
// This program demonstrates the length, charAt and getChars
// methods of the String class.
//
// Note: Method getChars requires a starting point
// and ending point in the String. The starting point is the
// actual subscript from which copying starts. The ending point
// is one past the subscript at which the copying ends.
import javax.swing.*;
public class StringMisc {
public static void main( String args[] )
{
String s1, output;
char charArray[];
s1 = new String( "hello there" );
charArray = new char[ 5 ];
// output the string
output = "s1: " + s1;
// test the length method
output += "\nLength of s1: " + s1.length();
// loop through the characters in s1 and display reversed
output += "\nThe string reversed is: ";
for ( int i = s1.length() - 1; i >= 0; i-- )
output += s1.charAt( i ) + " ";
// copy characters from string into char array
//四个参数的含义
//1.被拷贝字符在字串中的起始位置
//2.被拷贝的最后一个字符在字串中的下标再加1
//3.目标字符数组
//4.拷贝的字符放在字符数组中的起始下标
s1.getChars( 0, 5, charArray, 0 );
output += "\nThe character array is: ";
for ( int i = 0; i < charArray.length;i++ )
output += charArray[ i ];
JOptionPane.showMessageDialog( null, output,
"Demonstrating String Class Constructors",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}