【问题标题】:How can we print this output? [closed]我们如何打印这个输出? [关闭]
【发布时间】:2012-11-26 20:47:38
【问题描述】:
String x = "1 -7 2";
String y = "-2 2 1";

输出:

1,-2
-7,2
2,1

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

【问题讨论】:

  • 这三种语言真的不一样...
  • 请发布您目前拥有的代码,并解释什么没有按您的预期工作。
  • 神奇的自带分割功能...
  • 您需要 C、Java 或 VB.net 方面的帮助吗?
  • 所以使用与语言无关的标签,而不是一些随机标签。

标签: algorithm language-agnostic


【解决方案1】:

在 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

【讨论】:

    【解决方案2】:

    只是一个粗略的草图

    • 将空格处的两个字符串拆分为数组
    • 循环遍历这两个数组并一一合并

    【讨论】:

      【解决方案3】:

      对于 Java:

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

      【讨论】:

        【解决方案4】:

        java 中直接使用split 空间函数" "

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

        【讨论】:

          【解决方案5】:

          这处理 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();
          

          【讨论】:

            【解决方案6】:

            在 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]); 
            

            【讨论】:

              【解决方案7】:

              应该这样做:

              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]);
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2020-01-04
                • 1970-01-01
                • 2020-10-23
                • 1970-01-01
                • 2017-11-12
                • 1970-01-01
                • 1970-01-01
                • 2021-02-16
                相关资源
                最近更新 更多