华为OD机试题-java-华为机试题及答案

 1. 通过键盘输入任意一个字符串序列,字符串可能包含多个子串,子串以空格

分隔。请编写一个程序,自动分离出各个子串,并使用 ’,’ 将其分隔,并且在最后

也补充一个 ’,’ 并将子串存储

测试:输入:

“abc def gh i d”

输出:

“abc,def,gh,i,d,”
 

第一种方法: 

import java.util.Scanner;

public class Main1 {
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		
		// receive the input string.
		String inputStr = scan.nextLine();
		
		// split the string to array.
		String[] strArray = inputStr.split(" ");
		
		// add ","
		StringBuffer newSb = new StringBuffer();
		for(String str: strArray) {
			newSb.append(str);
			newSb.append(",");
		}
		
		// print output string.
		System.out.println(newSb.toString());
		
	}
}

第二种使用string 的replace

import java.util.Scanner;

public class Main2 {
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		
		// receive the input string.
		String inputStr = scan.nextLine();
		
		// replace " " by ","
		String newStr = inputStr.replace(" ", ",");
		
		// add "," in the end.
		newStr = newStr.concat(",");
		
		// print output string.
		System.out.println(newStr);
		
	}
}

你可能感兴趣的:(机试题,java,华为)