6、大小写转换
[变量名].toUpperCase();
//转换成大写
[变量名].toLowerCase();
//转换成小写
下面个例子:
public class a {
public static void main(String
args[])
{
String x="I LoVE You!";
System.out.println(x.toUpperCase());
System.out.println(x.toLowerCase());
}
}
输出结果:
I LOVE YOU!
i love you!
7、截取字符串
[字符串].substring([起始位置]);
[字符串].substring([起始位置],[结束位置]);
下面举个例子:
public class a{
public static void main(String
args[])
{
String
x="一个连自己都不相信的人是可悲的。";
System.out.println(x.substring(4));
System.out.println(x.substring(4,10));
}
}
运行结果:
自己都不相信的人是可悲的。
自己都不相信
这里值得提一下的是,在第二种方法中,结束位置并不包括结束位置上的字符,如本句中,就不包括”的“。
8、消除空格
[字符串].trim();
如:
public class a {
public static void main(String
args[])
{
String x="
I believe i n myse lf! ";
System.out.println(x.trim());
}
}
输出结果:
I believe i n myse lf!
二、StringBuffer类
StringBuffer [变量名] = new StringBuffer("[字符串]");
除了定义上是不同的,还有一个差别,那就是在对字符串操作时,String不会改变原有的字符串,而StringBuffer会把原来的字符串进行修改。
1、追加字符串
[字符串].append([字符串]);
这里就不举例了。
2、插入字符串
[字符串].insert([插入位置],[字符串]);
将后一个字符串插入到第一个字符串的指定位置。
如:
public class a {
public static void main(String
args[])
{
StringBuffer sb1 = new
StringBuffer("我的心在跳动。");
sb1.insert(4,"猛烈地");
System.out.println(sb1);
}
}
运行结果:
我的心在猛烈地跳动。
3、颠倒字符串
下面给格式:
[字符串].reverse();
举个例子:
public static void main(String
args[])
{
StringBuffer ch = new
StringBuffer("清华大学才是我的归宿!");
ch.reverse();
System.out.println(ch);
}
}
输出结果:
!宿归的我是才学大华清
好了,结束了,下面给个作业。
练习:
把每个操作都尝试一遍。
预告:
下面我们就要开始非常重要的学习了——流程控制。