1 回答

TA貢獻(xiàn)1963條經(jīng)驗 獲得超6個贊
首先,您需要用空格作為分隔符來劃分字符串并將它們存儲在字符串?dāng)?shù)組中,您可以通過編寫自己的代碼將一個字符串劃分為多個字符串來完成此操作,或者您可以使用名為的內(nèi)置函數(shù)split()
將字符串“拆分”為字符串?dāng)?shù)組后,只需迭代字符串?dāng)?shù)組,次數(shù)與最長字符串出現(xiàn)的次數(shù)相同,因為這是您要打印的最后一行(從共享輸出中可以理解),即,d來自 string Good,因此迭代字符串?dāng)?shù)組,直到打印最大/最長字符串中的最后一個字符,然后從那里退出。
您需要在迭代字符串?dāng)?shù)組時處理任何邊緣情況,例如沒有任何額外字符可供打印的字符串,但需要為下一個具有輸出順序字符的字符串打印空格。
以下是您可以參考的代碼段,但請記住在進(jìn)一步閱讀之前嘗試上面解釋的邏輯,
import java.io.*;
import java.util.*;
public class MyClass {
public static void main(String args[]) throws IOException{
//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Scanner sc = new Scanner(System.in);
String[] s = sc.nextLine().split(" ");
// Split is a String function that uses regular function to split a string,
// apparently you can strings like a space given above, the regular expression
// for space is \\s or \\s+ for multiple spaces
int max = 0;
for(int i=0;i<s.length;i++) max = Math.max(max,s[i].length()); // Finds the string having maximum length
int count = 0;
while(count<max){ // iterate till the longest string exhausts
for(int i=0;i<s.length;i++){
if(count<s[i].length()) System.out.print(s[i].charAt(count)+" "); // exists print the character
else System.out.print(" "); // Two spaces otherwise
}
System.out.println();count++;
}
}
}
編輯:我正在分享下面的字符串輸出This is a test Input
T i a t I
h s e n
i s p
s t u
t
添加回答
舉報