黑马程序员技术交流社区
标题:
字符串变量的使用、、新手入门、
[打印本页]
作者:
王楚鑫
时间:
2013-6-25 13:17
标题:
字符串变量的使用、、新手入门、
刚刚复习到字符串变量、、分享一下练习的代码、、常用的声明和操作的方法、、、进度差不多的童鞋来讨论下还有什么该狠狠记住的呢、、
public class Stringex{
public static void main(String[] args)
{
//----------声明创建字符串变量 ---------------
//(1).可以为字符串变量赋值简单的字符串常量来完成初始化
String str1="My number";
System.out.println(str1);
//(2). String()构造方法
String str2;
str2=new String(" is ");
System.out.println(str2);
//(3). String(byte[ ] bytes)构造方法
byte[] byteArray=new byte[]{52,49,51}; // 创建字节数组
String str3=new String(byteArray);
System.out.println(str3);
//(4). String(String charsetName)构造方法
String str4=new String(". ");
System.out.println(str4);
//-----------字符串操作---------------------------
//(1). 获取字符串长度
System.out.println("(1).The str1's length:"+str1.length());
//(2). 字符串查找
//indexOf(String s) 返回指定子字符串在此字符串中第一次出现处的索引
System.out.println("(2).The letter 'e' 's index: "+str1.indexOf("n"));
//(3). lastIndexOf(String str) 返回指定子字符串在此字符串中最右边出现处的索引。
System.out.println("(3).The letter 'r' 's the right index: "+str1.indexOf("r"));
//(4). 获取指定索引位置的字符
//str.charAt(int index)
System.out.println("(4). The index of 3's letter is: "+str1.charAt(3));
//(5). 获取子字符串
//substring(int beginIndex) 返回一个新的字符串,它是此字符串的一个子字符串。
System.out.println("(5).Behind the index of 3's substring is: "+str1.substring(3));
//substring(int beginIndex , int endIndex) 返回一个新字符串,它是此字符串的一个子字符串。
System.out.println("(5).Between the index 5 and 8's substring is: "+str1.substring(5,8));
//(6). 去除空格
//trim()方法返回字符串的副本,忽略前导空白和尾部空格
System.out.println("(6).After delete space,the new string is:"+str2.trim()+str3);
//(7).字符串替换
//str.replace(char oldChar,char newChar); replace()方法可实现将指定的字符或字符串替换成新的字符或字符串
System.out.println("(7).The new String is: "+str1.replace("My","my"));
//(8). 判断字符串是否相等str.equals(String otherstr)
//如果两个字符串具有相同的字符和长度,则使用equals()方法进行比较时,则返回true。
System.out.println("(8)."+str3.equals("413"));
//(9).字母大小写转换
System.out.println("(9)."+str1.toUpperCase());
System.out.println("MY name IS".toLowerCase());
//(10).字符串分割str.split(String sign)
String str5="Today is Tuesday.";
String[] newstr=str5.split(" ");
System.out.println("(10).The new string is:");
for(int i=0;i<newstr.length;i++)
{
System.out.println(newstr[i]);
}
}
}
复制代码
作者:
神之梦
时间:
2013-6-25 15:41
字符串是非常重要的,一定要弄懂弄会才行
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2