笔记(3):String中常见API的使用(一)

String中常见API(一)

1.查找字符串的长度

package com.tedu.String;

/**
 * length():返回当前字符串对象中字符的个数,实际上就是char类型数组的长度
 * 
 * @author Wildmess
 *
 */
public class StrLengthDemo {

	public static void main(String[] args) {
		String str = "a你b c";	//中国字,空格都算是一个字符
		System.out.println(str.length());//获得字符串的长度
		
	}
}

2.查找给定字符在字符串中位置

package com.tedu.String;

/**
 * indexOf(String str)
 * 查找给定字符在当前字符串中的位置
 * 若存在,返回给定字符串所在的索引位置
 * 没有则返回-1
 * lastIndexOf(String str)
 * 查找给定字符在当前字符串中的最后一个位置
 * @author Wildmess
 *
 */
public class IndexDemo {

	public static void main(String[] args) {
		String str = "this is java!";
		
		int index1 = str.indexOf("a");//查询字符串中第一个a出现的索引值
		System.out.println(index1);//9
		
		int index2 = str.indexOf("is");//俩个俩个查,得到第一个is是第二个
		System.out.println(index2);//2
		//若想找第二个
		index2 = str.indexOf("is",4);//从this后的空格开始
		System.out.println(index2);//5
		
		//找最后一个
		index2 = str.lastIndexOf("is");
		System.out.println(index2);
	}
}

3.截取字符串

package com.tedu.String;

/**
 * sunString(int start,int end)
 * 截取当前字符串中的内容
 * 按照留前不留后的规则
 * 返回截取到的内容
 * @author Wildmess
 *
 */
public class SubStringDemo {

	public static void main(String[] args) {
		String str = "abcdefghijklmn";
						// 01234567
		//截取字符串ghi(俩个参数留前不留后)
		//留前:g在字符串中对应索引号为6
		//留后:i在字符串中对应索引号为8
		//截取留下的就是第6个到第8个的内容
		String s = str.substring(6,9);
		System.out.println(s);
		
		//一个参数的表示从该位置截取到末尾
		s = str.substring(6);//ghijklmn
		System.out.println(s);
	}
}

API调用使用练习

package com.tedu.String;

/**
 * 定义一个类,对自己刚才学到的内容进行综合练习
 * @author Wildmess
 *
 */
public class StringTest {
	//定义几个域名
	//通过编写一个方法能够返回网址中的域名内容
	public static void main(String[] args) {
		String s1 = "www.baidu.com";//baidu
		String s2 = "http://www.tedu.cn";//tedu
		String s3 = "http://doc.tarena.com.cn";//tarena
		//要取出的内容是第一个点到第二个点之间的内容
		s1 = getHostName(s1);
		s2 = getHostName(s2);
		s3 = getHostName(s3);
		System.out.println(s1);
		System.out.println(s2);
		System.out.println(s3);
	}
	
	//定义一个方法取出一个字符串中i的一个点与第二个点之间的内容
	public static String getHostName(String url) {
		int start = url.indexOf(".") + 1;//获得要截取的起始位置
		int end = url.indexOf(".", start);//从start开始找到截取结束位置
//		String s = url.substring(start, end);
//		return s;
		return url.substring(start, end);
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值