设计一个方法,将一个字符串中每一个英文单词的首字母大写,返回一个新的字符串

学习后的练习内容,留个纪念~

/**
 * 设计一个方法,将一个字符串中每一个英文单词的首字母大写,返回一个新的字符串
 */
public class NewStr {

	public static void main(String[] args) {
		String str = "this is a text";
		String newString = "";
		// 切割字符串
		String[] arr = str.split(" ");
		for (String s : arr) {
			// 获取每个单词的首字母
			char ch = s.charAt(0);
			// 转化为大写字母
			char newCh = (char) (ch - 32);
			// 将每个被拆分后的单词定义给sb
			StringBuffer sb = new StringBuffer(s);
			// 将原单词的首个字母和大写字母交换
			sb.setCharAt(0, newCh);
			// 转换回string类型
			String newStr = sb.toString();
			newStr += " ";
			newString += newStr;
		}
		System.out.println(newString);
	}
}

运行结果:

可靠!

猜你喜欢

转载自blog.csdn.net/Ww1554487900/article/details/81366598
今日推荐