String练习题(字符串练习题):将每个单词的首字母改为大写
   
    
    
    使用String的方法
   
public static void main(String[] args) {
		String str = "this is a text"; 
		//方式一:将每个单词的首字母改为大写
		String[] str1 = str.split(" ");
		for (int i = 0; i < str1.length; i++) {
			String ch = str1[i].substring(0, 1).
				toUpperCase()+str1[i].substring(1);
			System.out.print(ch+" ");
		}
		//方式二:另一种方法的思路:提示大写字母与小写
		//字母相差32,如a = 97 A = 65,  注意空格要排除在外
		String str = "hello java and python!";
		String[] str1 = str.split(" ");
		for (int i = 0; i < str1.length; i++) {
			//将分隔开的每个单词的首字母减32得到大写字母
			char c = (char) (str1[i].charAt(0)-32);
			//将得到的大写字符与每个单词的小写字母拼接
			String s = c+str1[i].substring(1);
			System.out.print(s+" ");
		}
	}
    
    
    输出结果
   
    方式一:This Is A Text
    
    方式二:Hello Java And Python!
   
 
版权声明:本文为weixin_44906436原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。