1.字符串变量的创建
格式一
String <变量名>
<变量名>=new String("字符串");
eg:
String s; //声明字符串型引用变量s,此时s的值为null
s=new String("Hello"); //在堆内存中分配内存,并将s指向该字符串首地址
格式二
String <变量名> = new String("字符串");
eg:
String s=new String("hello");
格式三
String<变量名> = "字符串";
eg:
String s="hello";
java定义"+"运算符可用两个字符创的连接操作.
eg:str="hello"+"java"; // str的值为"hellojava"
如果字符串与其他类型的变量进行"+"运算,系统自动将其他类型转换为字符串类型.
eg:
int i=11;
String s="i="+i; //s的值为"i=11"
String类的常用方法
调用方法:
<字符串变量名>.<方法名>;
public int length() 返回字符串的长度
public boolean equals(Object anObject) 将给定字符串与当前字符串相比较,若两字符串相等则返回true,否返回false
public String substring( int beginIndex ) 返回字符串从beginIndex开始的字符串
public String substring( int beginIndex, int endIndex) 返回字符串从beginIndex开始到endIndex的子串
public char charAt(int index) 返回index指定位置的字符
public int indexOf( String str) 返回str在字符串中第一次出现的位置
public String replace( char oldChar, char newChar ) 以newChar字符串替换字符串中所有oldChar字符
public String trim() 去掉字符串的首尾空格
eg:判断回文字符串.
public class qpp5_6
{
public static oid main(String[] args)
{
String str="rotor";
int i=0,n;
boolean yn=true;
if(args.length>0)
{
str=args[0];
}
System.out.println("str="+str);
n=str.length();
char schar,echar;
while( yn && ( i<n/2 ) )// 算法1
{
scahr = str.charAt(i); //返回字符串str证书第i个位置的字符
echar = str.charAt(n-i-1); //返回字符串str倒数第i个位置的字符
System.out.println("schar="+schar+"echar="+echar);
if(schar == echar )
i++;
else
yn=false;
}
System.out.println("算法 1:" + yn );
String temp=" ",sub1=" "; //算法 2
for(i=0;i<n;i++)
{
sub1 = str.substring(i,i+1); //将str的第i个字符截取下来赋给sub1
temp = sub1 + temp;//将载下来的字符放在字符串temp的首位置
}
System.out.println("temp=" + temp);
System.out.println("算法2:"+str.equals(temp)); //判断str与temp是否相等
}
}
程序结果如下:
schar=h echar=o
算法1: false
temp = olleh
算法2:false