Logo

Programming-Idioms

  • Java
  • Obj-c

Idiom #71 Echo program implementation

Basic implementation of the Echo program: Print all arguments except the program name, separated by space, followed by newline.
The idiom demonstrates how to skip the first argument if necessary, concatenate arguments as strings, append newline and print it to stdout.

@import Foundation;
int main() {
  NSArray *all=NSProcessInfo.processInfo.arguments;
  NSArray *args=[all subarrayWithRange:NSMakeRange(1,all.count-1)];
  puts([args componentsJoinedByString:@" "].UTF8String);
  return 0;
}

The other solution is right (any plain-C code works in ObjC same way), but in practice, the object-oriented solution based on the Foundation library would be preferable
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
    while (*++argv) {
        printf("%s", *argv);
        if (argv[1]) printf(" ");
    }
    printf("\n");
    return EXIT_SUCCESS;
}
import static java.lang.String.join;
import static java.lang.System.out;
class Echo {
    public static void main(String[] args) {
        out.print(join(" ", args));
    }
}
import static java.lang.String.join;
import static java.lang.System.out;
public class Echo {
    public static void main(final String... args) {
        out.println(join(" ", args));
    }
}

String.join() exists only since Java 8.
with Ada.Command_Line; use Ada.Command_Line;
with Ada.Text_IO; use Ada.Text_IO;
procedure Main is
begin
   for I in 1 .. Argument_Count loop
      Put (Argument (I) & (if I = Argument_Count then "" else " "));
   end loop;
   
   New_Line;
end Main;

New implementation...
< >
christianhujer