Java applets enter a string, each word capitalized

Java applet 01

Enter a string, each word capitalized

1. First to receive incoming write a word, and passed word capitalized. This step is relatively simple, nothing to say!

	private String titleCase (String str) {  
		//转换操作,将传入的字符串的首字母取出后转换为大写,然后在传回
		String s = str.charAt(0)+"";
		s=s.toUpperCase();
		str=s+str.substring(1);
		return str;
	}

2. Write the first letter of each word receives a need to change the symbol string uppercase and delimited string of type String. Then split () method statement string str into words, in the array array, through the for loop, to separate good words are stored incoming titleCase (), and then to store the edited word by creating a StringBuilder.

	public String transformation(String str,String character) {
		//将传入的字符串已给定的字符串切割,然后进行处理
		String[] array = str.split(character);
		StringBuilder sbu = new StringBuilder();
		for (int i = 0; i < array.length; i++) {
			if(i!=0)
				sbu.append(" ");
			sbu.append(titleCase(array[i]));
		}
		return sbu.toString();
	}

The two main methods above

Here is the complete implementation of the code:

import java.util.*;
@SuppressWarnings("resource")
public class StringTransformation {
	private String str ;
	public StringTransformation(String str, String character) {
		inspect(str);
		inspect(character);
		this.str=transformation(str, character);
	}
	
	public String transformation(String str,String character) {
		//将传入的字符串已给定的字符串切割,然后进行处理
		String[] array = str.split(character);
		StringBuilder sbu = new StringBuilder();
		for (int i = 0; i < array.length; i++) {
			if(i!=0)
				sbu.append(" ");
			sbu.append(titleCase(array[i]));
		}
		return sbu.toString();
	}
	
	private String titleCase (String str) {  
		//转换操作,将传入的字符串的首字母取出后转换为大写,然后在传回
		String s = str.charAt(0)+"";
		s=s.toUpperCase();
		str=s+str.substring(1);
		return str;
	}
	
	private void inspect(String str) {
		if(str.length()<=0) {
			throw new IllegalArgumentException("字符串输入错误");
		}
	}
	
	@Override
	public String toString() {
		return this.str;
	}
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		System.out.println("请输入一个字符串,并用-作为分隔");
		String str = in.next();
		System.out.println(new StringTransformation(str,"-"));
	}
}
Published an original article · won praise 3 · Views 104

Guess you like

Origin blog.csdn.net/qq_41242174/article/details/104972319