您的位置:首页 > 编程语言 > Java开发

java基本入门-----String的基本操作

2013-09-19 09:57 441 查看
class String1
{
public static void method_get()   //获取
{
String str = "adasdff";
sop(str.length());
sop(str.charAt(2));
sop(str.indexOf('r'));   //找不到返回-1
sop(str.indexOf('d',3));  //从第3个位置索引
}

public static void method_is()   //包含
{
String str = "我喜欢你妹的";
sop(str.startsWith("我"));
sop(str.endsWith("妹的"));
sop(str.contains("我你"));   //if(str.indexOf("我你")!=-1)  即可判断又可获取出现的位置
}

/*转换
* 3.1将字符数组转换成字符串、
*    构造函数:String(char[])
*    		 String(char[],offset,count) :将字符数组一部分转换成字符串
* 3.2将字符串转换成数组
*   char[] toCharArray()
* 3.3将字节转成字符串
* 3.4将字符串转成字节
* 3.5将基本类型转成字符串
* 		static String valueOf(int)
* 		static String valueOf(double)
*/
public static void method_trans()
{
char[] arr = {'a','d','d','c','w'};

String str = new String(arr);
String str2 = new String(arr,1,3);
char[] a = str.toCharArray();
String str3 = "";
String str4 = str3.valueOf(345);
sop(str);
sop(str2);
sop(str4);

for(int x=0; x<a.length; x++)
{
sop(a[x]);
}
}

public static void method_replace()    //替换
{
String str = "java haha";
String str1 = str.replace('a', 'b');   //如果替换的没有找到,就返回原来的
String str2 = str.replace("haha","world");
sop(str1);
sop(str2);
}

public static void method_split()     //切割
{
String str = "sad efefsf tgrtg ee";
String[] str1 = str.split(" ");
for(int x=0; x<str1.length; x++)
{
sop(str1[x]);
}
}

public static void method_sub()
{
String str = "asdefff";
sop(str.substring(3));
sop(str.substring(3,6));
}

/*
* 7.1 将字符串转成大写或小写
*    String toUpperCase()
*    String tolowerCase()
* 7.2除去两端多余的空格
*    String trim()
* 7.3两个字符串比较 ask码
*    int compareTo(string)
* */

public static void method_7()
{
String s1 = "   asd FES  ";
String s2 = "   fsd  ";
sop(s1.toLowerCase());
sop(s1.toUpperCase());
sop(s1.trim());
sop(s1.compareTo(s2));   //a-f=-5    小于就是负数,大于就是正数
}

public static void main(String[] args)
{
//method_get();
//method_is();
//method_trans();
//method_replace();
//method_split();
//method_sub();
//method_7();
}

public static void sop(Object obj)
{
System.out.println(obj);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: