我们如何打印此输出?

时间:2012-11-26 20:47:38

标签: algorithm language-agnostic

String x = "1 -7 2";
String y = "-2 2 1";

输出:

1,-2
-7,2
2,1

我们将使用x的第一个数字,它是负数或正数,y是第一个数字......

7 个答案:

答案 0 :(得分:2)

在Java中,您可以使用Scanner类。

String integers = "1 -4 3";
Scanner sc = new Scanner(integers);
while(sc.hasNextInt())
{
    System.out.println(sc.nextInt();
}

在javadocs中查找:) http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

答案 1 :(得分:1)

只是粗略草图

  • 将白色空间的两个字符串拆分为数组
  • 遍历这两个数组并逐个合并

答案 2 :(得分:1)

对于Java:

您可以使用split方法拆分每个字符串,然后每个字符串都可以打印出每个数组中相应的字符。

答案 3 :(得分:1)

java中直接使用空间split

上的" "函数

c空间strtok上使用' '并将它们放入2个整数数组中,然后循环遍历它。 for odd iterations even迭代的第一个数组第二个数组并打印这些数字

答案 4 :(得分:1)

这涉及x和y大小不同的情况

    String x = "1 -7 2";
    String y = "-2 2 1";

    // Split the strings
    String[] xSplit = x.split("\\s+");
    String[] ySplit = y.split("\\s+");

    // Loop through them
    for (int i = 0; i < xSplit.length; i++) {
        System.out.print(xSplit[i] + " ");

        if (i < ySplit.length)
            System.out.print(ySplit[i] + " ");
    }

    // Print more y if needed
    for (int i = xSplit.length; i < ySplit.length; i++) {
        System.out.print(ySplit[i] + " ");
    }

    System.out.println();

答案 5 :(得分:1)

在C中执行此操作的简单方法:

char * x = "1 -7 2";
char * y = "-2 2 1";
int xs[3], ys[3];

sscanf(x, "%d %d %d", xs, xs+1, xs+2);
sscanf(y, "%d %d %d", ys, ys+1, ys+2);

printf("%d, %d\n%d, %d\n%d, %d\n", xs[0], ys[0], xs[1], ys[1], xs[2], ys[2]); 

答案 6 :(得分:0)

这应该做:

String[] splitX = x.split(" ");
String[] splitY = y.split(" ");

System.out.println(splitX[0]+","+splitY[0]);
System.out.println(splitX[1]+","+splitY[1]);
System.out.println(splitX[2]+","+splitY[2]);
相关问题