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); } }
原文链接:https://blog.csdn.net/Garensimida/article/details/119081174?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522165277696416781818717404%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fblog.%2522%257D&request_id=165277696416781818717404&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~blog~first_rank_ecpm_v1~times_rank-26-119081174-null-null.nonecase&utm_term=%E5%8D%8E%E4%B8%BA
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END