在过去的几天里,我一直在用JAVA练习问题,我得到了一个像这样的问题:
I/p: I Am A Good Boy
O/p:
I A A G B
m o o
o y
d这是我的代码。
System.out.print("Enter sentence: ");
String s = sc.nextLine();
s+=" ";
String s1="";
for(int i=0;i<s.length();i++)
{
char c = s.charAt(i);
if(c!=32)
{s1+=c;}
else
{
for(int j=0;j<s1.length();j++)
{System.out.println(s1.charAt(j));}
s1="";
}
}问题是我不能使这个design.My输出作为每行中的每个字符出现。
发布于 2019-09-08 10:24:53
首先,您需要使用空格作为分隔符来划分字符串,并将它们存储在字符串数组中。为此,您可以编写自己的代码将一个字符串划分为多个字符串,也可以使用一个名为split()的内置函数
将字符串‘分割’成字符串数组后,只需迭代字符串数组中出现的最长字符串的次数,因为这是您想要打印的最后一行(从共享的输出中可以理解),即string Good中的d,所以迭代字符串数组,直到打印最大/最长字符串中的最后一个最大字符,然后从那里退出。
在迭代字符串数组时,您需要处理任何边缘情况,比如没有任何额外字符要打印的字符串,但需要为下一个字符按输出顺序打印空格。
以下是你可以参考的代码片段,但在进一步阅读之前,请记住尝试上面解释的逻辑。
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 https://stackoverflow.com/questions/57838634
复制相似问题