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

From Coder Merlin
Line 27: Line 27:
== Java ==
== Java ==
<syntaxhighlight lang="java">
<syntaxhighlight lang="java">
// Unfinished code
// This is not the best code but it is easy to understand


String s = "ab3bk49dn3"; // random string
String s = "ab3bk49dn3"; // random string
String nums = ""; // string that will contain the numbers from s in order
String sAsInt = ""; // string that will contain the numbers from s in order
 
char[] numArray = {'0','1','2','3','4','5','6','7','8','9'}; // array with numbers as chars
// Convert s to a character array
char[] chars = s.toCharArray();


// Loop through all the chars to find the numbers
// Loop through all the chars to find the numbers
for(int i=0; i<chars.length; i++) {
for(char charecter: s.toCharArray()) {
   if(char[i] ==  
   for(char digit: numArray) {
      if(charecter == digit) sAsInt += x + ""; // add the digit on to the end of sAsInt
  }
}
}
</syntaxhighlight>
</syntaxhighlight>

Revision as of 18:55, 7 January 2020

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

Java[edit]

// This is not the best code but it is easy to understand

String s = "ab3bk49dn3"; // random string
String sAsInt = ""; // string that will contain the numbers from s in order
char[] numArray = {'0','1','2','3','4','5','6','7','8','9'}; // array with numbers as chars

// Loop through all the chars to find the numbers
for(char charecter: s.toCharArray()) {
   for(char digit: numArray) {
      if(charecter == digit) sAsInt += x + ""; // add the digit on to the end of sAsInt
   }
}

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 (size_t i = 0; i < line_length; i++) {
    if (isdigit(line[i])) {
      printf("%c\n",line[i]);
    }
  }

  return 0;
}