java基础练习

                   String str = "Nothing is impossible to a willing heart";

                   String str2 = "No cross, no crown.";

 

                   1, 打印整个字符串去掉所有空格之后的长度

public class Test {
	public static void main(String[] args) {
		String str = "Nothing is impossible to a willing heart";
		String str2 = "No cross, no crown.";
                System.out.println(str.replace(" ", "").length());//用replace替换空格。然后在打印长度。
         }
}    

 

                   2, 写代码找出字母"o","s"所在字符串str中第一次出现的索引位置, 找出字符串中最后一个"t"的索引位置, 并输出在控制台上

public class Test {
	public static void main(String[] args) {
		String str = "Nothing is impossible to a willing heart";
		String str2 = "No cross, no crown.";
                System.out.println(str . indexOf( "o") ) ;
	        System.out.println(str . indexOf( "s") ) ;
	        System.out.println(str . lastIndexOf( "t") ) ;
         }
}    

 

                   3, 写代码实现将str字符串用"空格"分割成数组, 并输出索引值为4的值

public class Test {
	public static void main(String[] args) {
		String str = "Nothing is impossible to a willing heart";
		String str2 = "No cross, no crown.";
                System.out.println(str.split(" ")[4]);//转换完后就是一个数组,直接在数组去索引值就可以
         }
} 

 前面是用空格分开的数组  最后的a是索引为4的值

                   4, 写代码实现将str字符串中所有的"i"替换成"I"

public class Test {
	public static void main(String[] args) {
		String str = "Nothing is impossible to a willing heart";
		String str2 = "No cross, no crown.";
                System.out.println(str.replace("i", "I"));
         }
} 

 

                   5, 编写代码从str字符串中取每个单词的首字母打印在控制台上

public class Test {
	public static void main(String[] args) {
		String str = "Nothing is impossible to a willing heart";
		String str2 = "No cross, no crown.";
                String[] strArray = str.split(" ");//把str分解为用空格隔开的几个数字(每个单词是一个数组)
	        for (int i = 0; i < strArray.length; i++) {
			 System.out.println(strArray[i].charAt(0));//获取新数组索引为0的值。
	        }
         }
} 

 

                   6, 在不使用第三个变量的情况下互换str和str2的值

方法一

public class Test {
	public static void main(String[] args) {
		String str = "Nothing is impossible to a willing heart";
		String str2 = "No cross, no crown.";
                System.out.println("str=" +str . replace(str,str2)) ;
	        System.out.println("str2=" +str2 . replace(str2,str)) ; 
         }
} 

 方法二

public class Test {
	public static void main(String[] args) {
		String str = "Nothing is impossible to a willing heart";
		String str2 = "No cross, no crown.";
		str += str2;//str和str2拼接    str=str+str2
		str2 = str.substring(0, str.length() - str2.length());//截取str从0到str长度减str2的长度相当于"Nothing is impossible to a willing heart No cross, no crown."-" No cross, no crown."
		str = str.substring(str2.length());//截取从str2长度(包括)开始相当于从" No cross, no crown."开始到最后
		System.out.println("str=" + str);
		System.out.println("str2=" + str2);
         }
} 

 

 

 

posted @ 2017-11-15 16:08  navyyouth  阅读(157)  评论(0编辑  收藏  举报