Difference between revisions of "Code Snippet: Print All Integers in a String"

From Coder Merlin
(Added print integers in "string" in C)
Line 24: Line 24:
</syntaxhighlight>
</syntaxhighlight>
[https://stackoverflow.com/a/354073/8292439 Source]
[https://stackoverflow.com/a/354073/8292439 Source]
== C ==
<syntaxhighlight lang="c">
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main( void ) {
  char *line;
  fgets(line, 255, stdin);
  size_t line_length = strlen(line);
  for (int i = 0; i < line_length; i++) {
    if (isdigit(line[i])) {
      printf("%c\n",line[i]);
    }
  }
  return 0;
}
</syntaxhighlight>

Revision as of 07:39, 23 May 2019

Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder

Print All Integers in a String[edit]

Swift[edit]

var line : String?
repeat {
    line = readLine()
    if let text = line {
        for character in text {
            if ("0" ... "9").contains(character) {
                print(character)
            }
        }
    }
} while line != nil

Python[edit]

string = input()
for char in string:
    if char.isdigit():
        print(char)

Source

C[edit]

#include <stdio.h>
#include <ctype.h>
#include <string.h>

int main( void ) {
  char *line;
  fgets(line, 255, stdin);

  size_t line_length = strlen(line);

  for (int i = 0; i < line_length; i++) {
    if (isdigit(line[i])) {
      printf("%c\n",line[i]);
    }
  }

  return 0;
}