Stringy Sting Verification

  • DonaldK 2012-06-27 10:36
    All the world's a string.

    Or a SubString... at the very least.
  • java.lang.Chris; 2012-06-27 10:40
    Sometimes a regexp really is the right answer ...
  • @Deprecated 2012-06-27 10:40
    Wow, so many inefficiencies I don't even know where to start!

    - Rebuilds array every time it is called
    - Uses an array instead of c >= '0' and c <= '9'
    - Calls substring repeatedly in inner loops
    - Does not exit early from outer for loop
    - Using strings instead of booleans

    Ugh. Maybe the array is used in case sometime in the future, a new number is added between '4' and '5'.
  • trtrwtf 2012-06-27 10:47
    Martin continues, "I'm not sure which is worse, the string return value of '0' or '1' or the ArrayList of numbers. I've found plenty of other similar functions but this is a nice standalone example.


    Ooh! Ooh! Pick me, I know!

    Is it when they use strings as booleans?


    (I'm thinking the use of the .Add() method and the .Length field has to be a simply [s]typo[/s]Microsoft being helpful... picking on them for that would be shooting ducks in a barrel)
  • @Deprecated 2012-06-27 10:49
    @Deprecated:
    Wow, so many inefficiencies I don't even know where to start!

    - Rebuilds array every time it is called
    - Uses an array instead of c >= '0' and c <= '9'
    - Calls substring repeatedly in inner loops
    - Does not exit early from outer for loop
    - Using strings instead of booleans

    Ugh. Maybe the array is used in case sometime in the future, a new number is added between '4' and '5'.


    Wait, WTF???
    bool validChars = true;
    and then 4 lines later:
    string matchedChar = "N";
  • emaN ruoY 2012-06-27 10:57
    Somebody has a very confused, multipersonal mind. First, as stated, sometimes RegEx really is the answer. Second, there are too many different styles in the code. As noted, using bool and string in the same method to indicate true/false.

    I half expect that the Caller probably sets a string variable and then through tedious manipulation turns it back into a boolean value.
  • airdrik 2012-06-27 10:57
    [s]There is no String, only Bool[/s]There is no Bool, only String
  • RaceProUK 2012-06-27 11:13
    emaN ruoY:
    First, as stated, sometimes RegEx really is the answer.

    Assuming the code is .NET, I think Int32.TryParse would be quicker. The method then becomes:

    private Boolean checkChars(string destination)
    {
    Int32 sink;
    return Int32.TryParse(destination, out sink);
    }

    Or, to keep the signature intact:


    private String checkChars(string destination)
    {
    Int32 sink;
    return Int32.TryParse(destination, out sink) ? "1" : "0";
    }
  • Alex 2012-06-27 11:14
    I think a loop with said "c >= '0' and c <= '9'" would beat the RegExp performance-wise.


    foreach (char c in input)
    {
    if ((c < '0') || (c > '9'))
    {
    LogDebug("Invalid character found")
    return false;
    }
    }
    LogDebug("Everything purrrrfect")
    return true;

  • dw 2012-06-27 11:15
    Maybe this function was originally a system call.

    That would explain the return value of "0" on success and "1" on failure.
  • Alex 2012-06-27 11:17
    This assumes that the string fits into a 32 bit signed integer (–2147483648 to 2147483647). An international phone number or some kind of account number could already exceed that limit.
  • MB 2012-06-27 11:20
    Surely int.parse will limit valid results to under 2147483647
  • TGV 2012-06-27 11:20
    Hey, you know student code is not a WTF! And this can't have been written by anyone with more than a week of programming experience. Right? Please?

    Or do you hire linguistic majors for your programming?
  • TGV 2012-06-27 11:21
    dw:
    Maybe this function was originally a system call.

    That would explain the return value of "0" on success and "1" on failure.

    Which system would that be???
  • dw 2012-06-27 11:23
    I meant "system call" in the sense of a call to an outside process like a BASH script. Sorry -- haven't been fully caffeinated yet.
  • Steve The Cynic 2012-06-27 11:25
    RaceProUK:
    emaN ruoY:
    First, as stated, sometimes RegEx really is the answer.

    Assuming the code is .NET, I think Int32.TryParse would be quicker.

    Nice try, but you need to exclude strings beginning with "-" in some way, as TryParse would presumably say that e.g. "-456" is valid...
  • Watson 2012-06-27 11:25
    @Deprecated:
    @Deprecated:
    Wow, so many inefficiencies I don't even know where to start!

    - Rebuilds array every time it is called
    - Uses an array instead of c >= '0' and c <= '9'
    - Calls substring repeatedly in inner loops
    - Does not exit early from outer for loop
    - Using strings instead of booleans

    Ugh. Maybe the array is used in case sometime in the future, a new number is added between '4' and '5'.


    Wait, WTF???
    bool validChars = true;
    and then 4 lines later:
    string matchedChar = "N";

    Yup; sorry to break it to you but there is something worse than using strings instead of booleans....
  • B. D. Johnson 2012-06-27 11:34
    Um, I think you'r forgetting about the "11" in 911.
  • ahydra 2012-06-27 11:47
    "Ugh. Maybe the array is used in case sometime in the future, a new number is added between '4' and '5'."

    I think I'll change my phone number to 07709 34724½8¾. No way telemarketers will find me then!
  • Zylon 2012-06-27 11:49
    WTF is "Sting Verification"?
  • Jamie 2012-06-27 11:56
    My 2 year old seems to thing 6 comes between 4 and 5...
  • LabSpecimen 2012-06-27 12:01
    We had fun with this one at work. Here's my version:

    private boolean checkChars(string destination)
    {
    int cnt = 0;
    if (destination != null)
    {
    for (int i = 0; i < destination.length(); i++)
    {
    (destination.charAt(i) == '0') ?
    cnt++ : (destination.charAt(i) == '1') ?
    cnt++ : (destination.charAt(i) == '2') ?
    cnt++ : (destination.charAt(i) == '3') ?
    cnt++ : (destination.charAt(i) == '4') ?
    cnt++ : (destination.charAt(i) == '5') ?
    cnt++ : (destination.charAt(i) == '6') ?
    cnt++ : (destination.charAt(i) == '7') ?
    cnt++ : (destination.charAt(i) == '8') ?
    cnt++ : (destination.charAt(i) == '9') ?
    cnt++ : cnt = cnt;
    }
    }
    return (destination != null && cnt == destination.length()) ? true : false;
    }
  • C-Derb 2012-06-27 12:01
    @Deprecated:
    Wow, so many inefficiencies I don't even know where to start!
    ...
    - Does not exit early from outer for loop
    ...

    If the code exited from the outer loop as soon as the first invalid character was found, then the debug log would not give a full report of ALL invalid characters in the destination string.
    Clearly a verbose and accurate debug log is worth the price of completing the outer loop, um, right?
  • Harrow 2012-06-27 12:15
    @Deprecated:
    Wow, so many inefficiencies I don't even know where to start!

    - Rebuilds array every time it is called
    - Uses an array instead of c >= '0' and c <= '9'
    - Calls substring repeatedly in inner loops
    - Does not exit early from outer for loop
    - Using strings instead of booleans

    Ugh. Maybe the array is used in case sometime in the future, a new number is added between '4' and '5'.
    The Nobel Prize in Mathematics has been awarded to a California professor who has discovered a new number. The number is "bleen" which he claims belongs between six and seven. --George Carlin, The New News

    -Harrow.
  • redmasq 2012-06-27 12:17
    If only the validity of characters I would do something like:

    using System.Text.RegularExpressions;

    public class Blah {
    private static readonly Regex CharCheck = new Regex("[^0-9]");
    private bool CheckCharacters(string destination) {
    return !(CharCheck.Match(destination).Success);
    }
    }

    Syntax looked C#'ish, so wrote in that syntax, but similar could be done in Java.

    Making it static means only one instance of the regex running. If used a lot, I'd probably add the compiled flag. In practice I haven't seen any threading issues with doing similar, but I would double check for a critical application since only the static methods are guaranteed thread-safe (Match is used as an instance method in this case). The readonly flag should help the compiler with optimizations.

    If the logging is needed, just modify to keep the value of success, and use the Matches method instead: iterate thru the returned collection, logging as appropriate.

    Just my two-cents.
  • Zmee 2012-06-27 12:28
    Just wow! And replacing this with a single line:
    return java.util.regex.Pattern.matches("^\\d*$", destination);

    (And yes, it is d* rather than d+; there is no requirement for the string to be non-empty.)
  • bene 2012-06-27 12:28
    airdrik:
    [s]There is no String, only Bool[/s]

    You surely mean "Zuul"?
  • area driver 2012-06-27 12:30
    @Deprecated:

    Ugh. Maybe the array is used in case sometime in the future, a new number is added between '4' and '5'.


    Hi Depricated, are you free for lunch on the Fouivth of Smarch?
  • foo 2012-06-27 12:38
    emaN ruoY:
    Somebody has a very confused, multipersonal mind. First, as stated, sometimes RegEx really is the answer. Second, there are too many different styles in the code. As noted, using bool and string in the same method to indicate true/false.
    And even two different string Booleans (N/Y and 0/1).

    (Yeah, and none of them includes FILE_NOT_FOUND, blah.)
  • C-Derb 2012-06-27 12:46
    Mmmm...I love me some recursion:

    private bool ContainsChars(string destination)
    
    {
    if (string.IsNullOrEmpty(destination)) return false;
    int i;
    return int.TryParse(destination.Substring(0, 1), out i) ? ContainsChars(destination.Substring(1)) : true;
    }
  • pauly 2012-06-27 12:48
    This looks like pre-optimization code. You write functions like this so you can rewrite them in the future when the boss demands the code runs faster and uses less memory. This is more clever than using some sort of wait function, as it really does increase the CPU rather than artificially slowing it down.
  • Matt 2012-06-27 12:57
    return Regex.Match("[\d]", destination).Success;
  • Nappy 2012-06-27 13:09
    Written by the guy who gets payed per log line checked?
  • M 2012-06-27 13:21
    C# with extension method and lambda:

    private static bool ContainsNonDigits(this string destination)
    {
    return destination.Any(c => c < '1' || c > '9');
    }

    Example:

    string foo = "abc123";
    if (foo.ContainsNonDigits())
    {
    Blah, blah, blah...
    }
  • Kristopher Ives 2012-06-27 13:22
    A man once mad regular expressions. That apparently wasn't this man. Honestly dropping this in my list of "stuff you do without regex"
  • M 2012-06-27 13:25
    M:
    C# with extension method and lambda:

    private static bool ContainsNonDigits(this string destination)
    {
    return destination.Any(c => c < '1' || c > '9');
    }

    Example:

    string foo = "abc123";
    if (foo.ContainsNonDigits())
    {
    Blah, blah, blah...
    }


    ... or public if you want to use it outside the class it's defined in. :)
  • Nagesh 2012-06-27 13:26
    LabSpecimen:
    We had fun with this one at work. Here's my version:

    private boolean checkChars(string destination)
    {
    int cnt = 0;
    if (destination != null)
    {
    for (int i = 0; i < destination.length(); i++)
    {
    (destination.charAt(i) == '0') ?
    cnt++ : (destination.charAt(i) == '1') ?
    cnt++ : (destination.charAt(i) == '2') ?
    cnt++ : (destination.charAt(i) == '3') ?
    cnt++ : (destination.charAt(i) == '4') ?
    cnt++ : (destination.charAt(i) == '5') ?
    cnt++ : (destination.charAt(i) == '6') ?
    cnt++ : (destination.charAt(i) == '7') ?
    cnt++ : (destination.charAt(i) == '8') ?
    cnt++ : (destination.charAt(i) == '9') ?
    cnt++ : cnt = cnt;
    }
    }
    return (destination != null && cnt == destination.length()) ? true : false;
    }


    Not much work at your work, I see.
  • oops 2012-06-27 13:31
    M:
    C# with extension method and lambda:

    private static bool ContainsNonDigits(this string destination)
    {
    return destination.Any(c => c < '1' || c > '9');
    }

    Example:

    string foo = "abc123";
    if (foo.ContainsNonDigits())
    {
    Blah, blah, blah...
    }


    Better to do:
    return destination.Any(c => !char.IsDigit(c));

    IsDigit never forgets that 0 is a digit too, even though it is also < '1'.
  • Octavian 2012-06-27 14:00
    oops:
    M:
    C# with extension method and lambda:

    private static bool ContainsNonDigits(this string destination)
    {
    return destination.Any(c => c < '1' || c > '9');
    }

    Example:

    string foo = "abc123";
    if (foo.ContainsNonDigits())
    {
    Blah, blah, blah...
    }


    Better to do:
    return destination.Any(c => !char.IsDigit(c));

    IsDigit never forgets that 0 is a digit too, even though it is also < '1'.


    But I want to call it with Ⅷ.
  • M 2012-06-27 14:01
    i did some actual testing of this one (in Java, see code below) and the results really speak for themselves (each method called 2M times):

    Enterprisey: 19858
    simple: 192



    import java.util.ArrayList;

    public class Test {

    public static void main(String[] args) {
    String s = "193485923905820394029850298402983409284032840238402984";
    String t = "34534534503985039845038450394850394850398503498503985a";
    long l = System.currentTimeMillis();
    for (int i = 0; i < 1000000; i++) {
    checkChars(s);
    checkChars(t);
    }
    l = System.currentTimeMillis() - l;
    System.out.println("Enterprisey: " + l);

    l = System.currentTimeMillis();
    for (int i = 0; i < 1000000; i++) {
    checkChars2(s);
    checkChars2(t);
    }
    l = System.currentTimeMillis() - l;
    System.out.println("simple: " + l);

    }

    private static boolean checkChars2(String in) {

    for (char c : in.toCharArray()) {
    if (!(c >= '0' && c <= '9')) {
    return false;
    }
    }

    return true;
    }

    private static String checkChars(String destination) {
    ArrayList<String> validCharacters = new ArrayList<String>();

    validCharacters.add("0");
    validCharacters.add("1");
    validCharacters.add("2");
    validCharacters.add("3");
    validCharacters.add("4");
    validCharacters.add("5");
    validCharacters.add("6");
    validCharacters.add("7");
    validCharacters.add("8");
    validCharacters.add("9");

    boolean validChars = true;

    for (int i = 0; i < destination.length(); i++) {
    String matchedChar = "N";

    for (String character : validCharacters) {
    if (destination.substring(i, i + 1) == character) {
    matchedChar = "Y";

    break;
    }
    }

    if (matchedChar == "N") {
    LogDebug("checkChars -> Invalid character found: " + destination.substring(i, i + 1));

    validChars = false;
    }
    }

    String charStatus;

    if (validChars) {
    LogDebug("checkChars -> All characters ok");

    charStatus = "0";
    } else {
    LogDebug("checkChars -> Invalid characters found");

    charStatus = "1";
    }

    return charStatus;
    }

    private static void LogDebug(String string) {
    }

    }
  • Ello 2012-06-27 14:04
    Why not ask Zoidberg and usw

    if (Regex.IsMatch(input, "^[0-9 ]+$"))
    return true;
  • Illuminati 2012-06-27 14:15
    Its not between 4 and 5 it's between 3 and 4 and its called bleem:

    http://www.strangehorizons.com/2000/20001120/secret_number.shtml

    Now that you know they'll try and kill you to keep it secret!
  • Jimmy Carter 2012-06-27 14:15
    M:
    i did some actual testing of this one (in Java, see code below) and the results really speak for themselves (each method called 2M times):

    Enterprisey: 19858
    simple: 192



    import java.util.ArrayList;

    [snip]



    You left out the logging. Logging was clearly specified in the requirements document.
  • Speakerphone Dude 2012-06-27 14:24
    @Deprecated:

    Maybe the array is used in case sometime in the future, a new number is added between '4' and '5'.


    This could also be hugely convenient at some point in the future if
    7 8 9!

  • R 2012-06-27 14:30
    Or just regex /\d+/
  • Zylon 2012-06-27 14:51
    bene:
    airdrik:
    [s]There is no String, only Bool[/s]

    You surely mean "Zuul"?

    You are dumb.
  • Aargle Zymurgy 2012-06-27 14:51
    Years ago when I started teaching, I already knew programmers would just code the very first thing that occurred to them to solve a problem. I think I had a small measure of success when I told them "If you can't think of at least two ways to do what you're trying to do, you're not actually thinking about the problem. Sure, you might think of some really bad way to solve the problem, but at least you've got something to compare your other idea to. You can improve from there."
  • operagost 2012-06-27 15:14
    TGV:
    dw:
    Maybe this function was originally a system call.

    That would explain the return value of "0" on success and "1" on failure.

    Which system would that be???

    An embedded system with no storage space, of course.
  • Linux Pro 2012-06-27 15:15
    I fear that performance-wise it doesn't even matter.
  • Wetlands 2012-06-27 15:49
    Add logging and change the return type if you need to but the basic functionality is:

    return s.ToCharArray().Any(c => "1234567890".Contains(c) == false);
  • da Doctah 2012-06-27 16:07
    Zylon:
    WTF is "Sting Verification"?

    Many miles away
    Something crawls from the slime
    At the bottom of a dark Scottish lake
  • AGray 2012-06-27 16:24
    C-Derb:
    Mmmm...I love me some recursion:

    private bool ContainsChars(string destination)
    
    {
    if (string.IsNullOrEmpty(destination)) return false;
    int i;
    return int.TryParse(destination.Substring(0, 1), out i) ? ContainsChars(destination.Substring(1)) : true;
    }


    I love me some recursion too, but recursion is slow; is that really the best way to validate the string?

    class Example
    
    {
    private List<string> forbidden = new List<string> {0,1,2,3,4,5,6,7,8,9};

    public string ContainsChars(string destination)
    {
    for(int i = 0; i < destination.Length; i++)
    {
    if(forbidden.Contains(destination[i])
    {
    return "0";
    }
    }

    return "1";
    }
    }


    I think that would be a bit cleaner.

    CAPTCHA: Persto - Presto when said frist!
  • PRMan 2012-06-27 16:46
    @Deprecated:
    Wow, so many inefficiencies I don't even know where to start!

    - Rebuilds array every time it is called
    - Uses an array instead of c >= '0' and c <= '9'
    - Calls substring repeatedly in inner loops
    - Does not exit early from outer for loop
    - Using strings instead of booleans

    Ugh. Maybe the array is used in case sometime in the future, a new number is added between '4' and '5'.


    Such as Derf...
  • Ryan 2012-06-27 16:48
    Looks like a good place to use Regular Expressions (try http://www.ultrapico.com/Expresso.htm).

    Additionally it validates an empty destination of string.empty since validChars defaults to true, which probably isn't the intended behavior and would help your case for cleaning it up.
  • C-Derb 2012-06-27 17:01
    AGray:

    I love me some recursion too, but recursion is slow; is that really the best way to validate the string?

    No, recursion is not the best way for this particular validation requirement. I was merely throwing it out there as yet another approach. But, to be fair, it is better than the original "solution".
  • SG_01 2012-06-27 17:23
    return destination.All(x => char.IsNumber(x));

    Was that so hard? (Note that this allows numbers that cannot be parsed on the system due to them being too large)
  • AGray 2012-06-27 17:23
    C-Derb:
    AGray:

    I love me some recursion too, but recursion is slow; is that really the best way to validate the string?

    No, recursion is not the best way for this particular validation requirement. I was merely throwing it out there as yet another approach. But, to be fair, it is better than the original "solution".


    Fair point.

    CAPTCHA: consequat - a Sasquatch-sized consequence of writing bad code!
  • Dathan 2012-06-27 17:50
    AGray, you realize your method is completely wrong, right?
  • SG_01 2012-06-27 18:26
    Ryan:
    Looks like a good place to use Regular Expressions (try http://www.ultrapico.com/Expresso.htm).



    Hrmm, this looks amazing, no idea that existed *grabs*
  • JJ 2012-06-27 18:31
    Matt:
    return Regex.Match("[\d]", destination).Success;

    Let me count the fail.

    1) Your input and pattern parameters are in the wrong order. The pattern comes second.

    2) Compiler error: Unrecognized escape sequence. Put @ in front of the pattern or double the backslash.

    3) Your pattern will match any string with a number in it anywhere.
  • Oops 2012-06-27 18:58
    SG_01:
    return destination.All(x => char.IsNumber(x));

    Was that so hard? (Note that this allows numbers that cannot be parsed on the system due to them being too large)


    Hard? No.
    Correct? Also No.

    These calls will both return true with your version:
    checkChars("ⅮⅠⅯⅱ");
    checkChars("⅞፼൱");

    IsDigit is what you wanted here.
  • Oops 2012-06-27 19:07
    Oops:
    SG_01:
    return destination.All(x => char.IsNumber(x));

    Was that so hard? (Note that this allows numbers that cannot be parsed on the system due to them being too large)


    Hard? No.
    Correct? Also No.

    These calls will both return true with your version:
    checkChars("ⅮⅠⅯⅱ");
    checkChars("⅞፼൱");

    IsDigit is what you wanted here.


    Oops..I got it wrong too. There are 460 digit chars in unicode.

    Guess we gotta go with:
    destination.All(x => x >= '0' && x <= '9');


  • ozzie 2012-06-27 19:08
    Oh I see the problem, he didn't use xml.
  • User.FullName 2012-06-27 19:25
    I tried texting 1-800-suicide and my phone told me my very character is invalid. _esteem--;
  • SG_01 2012-06-27 19:47
    Oops:
    Oops:
    SG_01:
    return destination.All(x => char.IsNumber(x));

    Was that so hard? (Note that this allows numbers that cannot be parsed on the system due to them being too large)


    Hard? No.
    Correct? Also No.

    These calls will both return true with your version:
    checkChars("ⅮⅠⅯⅱ");
    checkChars("⅞፼൱");

    IsDigit is what you wanted here.


    Oops..I got it wrong too. There are 460 digit chars in unicode.

    Guess we gotta go with:
    destination.All(x => x >= '0' && x <= '9');




    The only requirement stated was that the thing only contained numbers, which is exactly what it does. I never said it matched what the code does :D
  • bob 2012-06-27 20:11
    Getting paid by the line surely...
  • SG_01 2012-06-27 20:20
    Well, if you were parsing phone numbers, you'd have to at least have something along the lines of:

    ^( *\+ *[0-9]+)?( *\( *[0-9]+ *\))( *[0-9]+| *- *[0-9]+)* *$

    Of course in this, the characters (, ), - and space get removed, + gets replaced by whatever the international dialling code is, however before that you might want to remove the entire international block all together if it's for the current country. However if this is the case, you will need to insert an extra 0 for some countries. Also, if you want to do this, you'll need to figure out the exact length of the country code, making it become something like:

    *\+ *(1|[2-4][0-9]|...)

    Then you get the locational area, this is usually the first block after the internal code, and may be omitted to dial local... This is usually the part between the parentheses, however as users tend to get this part wrong. In the end, this requires a whole separate parsing round, so you may as well have been writing your own parser for this.

    If you want to support letters, you can do that in the last couple of blocks as well, but then you'll need to convert them to numbers as well.

    TL;DR: Phone numbers: A whole lot harder than your simple 0-9 digit parsing.
  • barf 4eva 2012-06-27 21:35
    Damn.... that's pretty fkn bad..
  • KaeruCT 2012-06-27 22:05
    Yeah, because you couldn't just have used regex
  • Everyone's a critic 2012-06-27 22:33
    Does it work? Yes.
  • Dick Head 2012-06-27 23:06
    Zylon:
    WTF is "Sting Verification"?

    A determination of whether any song has repetitive, nonsensical lyrics towards the end. I guess a regex could be used here somehow.
  • Mathlete 2012-06-28 00:19
    TRWTF is that almost every "fixed" version in this comments thread is wrong! You could get at least a week's worth of articles from it.

    This will maintain the current logging and return type while removing the stupid:

    private string checkChars(string destination)
    {
    var invalidChars = destination.Where(x => x < '0' || x > '9').ToList();

    if (invalidChars.Any())
    {
    foreach (var invalidChar in invalidChars)
    LogDebug("checkChars -> Invalid character found: " + invalidChar);
    LogDebug("checkChars -> Invalid characters found");

    return "1";
    }

    LogDebug("checkChars -> All characters ok");

    return "0";
    }


    Of course if you just want a boolean, you could use any of the following:



    public bool CheckChars(string destination) { return destination.All(x => '0' <= x && x <= '9'); }

    public bool CheckChars(string destination) { return Regex.IsMatch(destination, @"^\d*$"); }

    public bool CheckChars(string destination)
    {
    foreach (var c in destination)
    {
    if (c < '0' || c > '9')
    return false;
    }

    return true;
    }

  • lietu 2012-06-28 00:39
    In many "modern" languages this could be simplified basically to something like:
    return (string)(int)destination === destination

    E.g. in JavaScript:
    return String(parseInt(destination, 10)) === destination
  • Mr Obvious 2012-06-28 00:46
    LabSpecimen:
    We had fun with this one at work. Here's my version:

    private boolean checkChars(string destination)
    {
    int cnt = 0;
    if (destination != null)
    {
    for (int i = 0; i < destination.length(); i++)
    {
    (destination.charAt(i) == '0') ?
    cnt++ : (destination.charAt(i) == '1') ?
    cnt++ : (destination.charAt(i) == '2') ?
    cnt++ : (destination.charAt(i) == '3') ?
    cnt++ : (destination.charAt(i) == '4') ?
    cnt++ : (destination.charAt(i) == '5') ?
    cnt++ : (destination.charAt(i) == '6') ?
    cnt++ : (destination.charAt(i) == '7') ?
    cnt++ : (destination.charAt(i) == '8') ?
    cnt++ : (destination.charAt(i) == '9') ?
    cnt++ : cnt = cnt;
    }
    }
    return (destination != null && cnt == destination.length()) ? true : false;
    }

    Ummm... it looks like one of your variables is missing the letter 'u'.
  • lietu 2012-06-28 00:46
    Mathlete:
    Of course if you just want a boolean, you could use any of the following:


    .. if instead of boolean you want "1" or "0", why not just add ?"1":"0" or whichever way they wanted the return value ..
  • Matt Westwood 2012-06-28 01:16
    @Deprecated:
    Wow, so many inefficiencies I don't even know where to start!

    - Rebuilds array every time it is called
    - Uses an array instead of c >= '0' and c <= '9'
    - Calls substring repeatedly in inner loops
    - Does not exit early from outer for loop
    - Using strings instead of booleans

    Ugh. Maybe the array is used in case sometime in the future, a new number is added between '4' and '5'.


    Oh, du-uh! I'll pick one for you, then you work out whether you can do likewise. Ready? Set? Go!

    4.5
  • Matt Westwood 2012-06-28 01:19
    Mr Obvious:
    LabSpecimen:
    We had fun with this one at work. Here's my version:

    private boolean checkChars(string destination)
    {
    int cnt = 0;
    if (destination != null)
    {
    for (int i = 0; i < destination.length(); i++)
    {
    (destination.charAt(i) == '0') ?
    cnt++ : (destination.charAt(i) == '1') ?
    cnt++ : (destination.charAt(i) == '2') ?
    cnt++ : (destination.charAt(i) == '3') ?
    cnt++ : (destination.charAt(i) == '4') ?
    cnt++ : (destination.charAt(i) == '5') ?
    cnt++ : (destination.charAt(i) == '6') ?
    cnt++ : (destination.charAt(i) == '7') ?
    cnt++ : (destination.charAt(i) == '8') ?
    cnt++ : (destination.charAt(i) == '9') ?
    cnt++ : cnt = cnt;
    }
    }
    return (destination != null && cnt == destination.length()) ? true : false;
    }

    Ummm... it looks like one of your variables is missing the letter 'u'.


    Reminds me of someone's FORTRAN program when I was considerably younger: dSylelixc colleague wanted to use NCOUNT as a variable but instead transposed the 2nd and 3rd letters. Oh how we laughed.
  • Mathlete 2012-06-28 01:58
    lietu:
    Mathlete:
    Of course if you just want a boolean, you could use any of the following:


    .. if instead of boolean you want "1" or "0", why not just add ?"1":"0" or whichever way they wanted the return value ..


    Because the equivalent version I posted has multiple return statements? If it had a valid flag and a single return then obviously I would have used
    return valid ? "0" : "1";



    Also out of curiosity I also ran the following benchmark code:


    public static void Main(string[] args)
    {
    const string valid = "193485923905820394029850298402983409284032840238402984";
    const string invalid = "34534534503985039845038450394850394850398503498503985a";

    foreach (var func in new Func<string, bool>[] { ValidateLinq, ValidateRegex, ValidatePrecompiledRegex, ValidateForLoop })
    {
    var startTime = DateTime.Now;

    for (var i = 0; i < 1000000; i++)
    {
    func(valid);
    func(invalid);
    }

    var endTime = DateTime.Now;

    Console.Out.WriteLine(func.Method.Name + ": " + endTime.Subtract(startTime).TotalMilliseconds);
    }

    Console.In.ReadLine();
    }

    private static bool ValidateLinq(string str) { return str.All(x => '0' <= x && x <= '9'); }

    private static bool ValidateRegex(string str) { return Regex.IsMatch(str, @"^\d*$"); }

    private static readonly Regex ValidatorRegex = new Regex(@"^\d*$");
    private static bool ValidatePrecompiledRegex(string str) { return ValidatorRegex.IsMatch(str); }

    private static bool ValidateForLoop(string str)
    {
    foreach (var c in str) if (c < '0' || c > '9') return false;
    return true;
    }


    The results were interesting:

    ValidateLinq: 1239
    ValidateRegex: 6241
    ValidatePrecompiledRegex: 5449
    ValidateForLoop: 171
  • Peter Olsen 2012-06-28 03:00
    Actually, a new integer between 3 and 4 have recently been found in Denmark.

    http://translate.google.com/translate?sl=auto&tl=en&js=n&prev=_t&hl=en&ie=UTF-8&layout=2&eotf=1&u=http%3A%2F%2Frokokoposten.dk%2F2011%2F10%2F14%2Fbreaking-heltal-mellem-3-og-4-fundet-naer-silkeborg%2F&act=url
  • Benny Bottema 2012-06-28 03:00
    not to mention the == equality checks with Strings.
  • Jan 2012-06-28 03:20
    @Deprecated:
    Ugh. Maybe the array is used in case sometime in the future, a new number is added between '4' and '5'.


    You laugh now, but just wait I tell you, you'll see, you'll all see!
  • erikr 2012-06-28 04:14
    I guess a company selling text-based services like to use a text-based approach when coding...
  • Stev 2012-06-28 04:33
    M:
    i did some actual testing of this one (in Java, see code below)


    And the award for TRWTF goes to...
  • Jibble 2012-06-28 05:06
    @Deprecated:
    Wow, so many inefficiencies I don't even know where to start!


    Don't worry, Moore's law will soon take up the slack.
  • Derp 2012-06-28 05:27
    And I thought MY code was bad.
  • Derp 2012-06-28 05:29
    Alex:
    I think a loop with said "c >= '0' and c <= '9'" would beat the RegExp performance-wise.


    foreach (char c in input)
    {
    if ((c < '0') || (c > '9'))
    {
    LogDebug("Invalid character found")
    return false;
    }
    }
    LogDebug("Everything purrrrfect")
    return true;



    This is correct. In fact this is about a thousand times faster than Regex.IsMatch(string, @"\d+");
  • Pero Perić 2012-06-28 05:58
    @Deprecated:
    Wow, so many inefficiencies I don't even know where to start!

    - Rebuilds array every time it is called
    - Uses an array instead of c >= '0' and c <= '9'
    - Calls substring repeatedly in inner loops
    - Does not exit early from outer for loop
    - Using strings instead of booleans

    Ugh. Maybe the array is used in case sometime in the future, a new number is added between '4' and '5'.

    Using collection of valid chars instead of boolean expression is more maintainable approach. Judging by the method name, arbitrary set of chars can be considered valid. The article text doesn't specify the number format and we all know that there are many way to represent a number as string. Signs, decimal separators, thousands separators, scientific notation (char 'e' is perfectly valid there), special values such as infinity and NaN. Rebuilding array every time reduces performance but is not as wrong as other WTFs in that code snippet, it makes the code more copy paste frendly :P.

    There should be a international law against using non-boolean values for clearly boolean output in high level languages (C and higher despite C being considered low level these days). It's not likely the method in question would be required to return "X" (undefined) or "Z" (high impedance) in future :). Using 0/1 and Y/N is not all that can be encountered in this kind of string abuse, toss in case variation (y/n, y/N, Y/n), language variation (D/N, J/N), full words (yes/now, da/ne, ja/nein...) and you be running a freak show circus. Using ints instead of bools should be also prohibited by that law.

    Anyway, regex that passes Turkish test would suffice in this case. There is a nice example in one comment how to find illegal chars using .Net Regex class. Turkish test is important, don't skip that part.
  • ped 2012-06-28 07:55
    Derp:
    Alex:
    I think a loop with said "c >= '0' and c <= '9'" would beat the RegExp performance-wise.


    foreach (char c in input)
    {
    if ((c < '0') || (c > '9'))
    {
    LogDebug("Invalid character found")
    return false;
    }
    }
    LogDebug("Everything purrrrfect")
    return true;



    This is correct. In fact this is about a thousand times faster than Regex.IsMatch(string, @"\d+");


    So, lowest level language (looks like C to me!) is best. Again, OOP is the real WTF!
  • Todd Lewis 2012-06-28 08:16
    TGV:
    Hey, you know student code is not a WTF! And this can't have been written by anyone with more than a week of programming experience. Right? Please?

    Or do you hire linguistic majors for your programming?


    Hey, wait a second. I'm a "linguistic major" and I've been coding for over 30 years... and... I've... written a lot of crappy code in those years.

    Yeah, okay, I see your point.
  • Derp 2012-06-28 08:25
    ped:
    So, lowest level language (looks like C to me!) is best. Again, OOP is the real WTF!

    There's nothing inherently wrong with OOP. It's just used improperly in about 99.9453248% of cases.
  • Stark 2012-06-28 09:21
    Apparently, you did know where to start! :-)

    And, how to finish!

    Good one.
  • Thomas 2012-06-28 10:01
    java.lang.Chris;:
    Sometimes a regexp really is the right answer ...


    ctype_digit()
  • DoctorToxn 2012-06-28 10:38
    No no no! You just don't get it! He was getting ready for when all the kids grow up and "L33T Speak" is all they can write! This guy was a really forward thinking Brillant Suuuuuuuuuupppperrrrr Geeeeeeeeennniuuuuusssss.


    validCharacters.Add("0");
    validCharacters.Add("O");
    validCharacters.Add("o");
    validCharacters.Add("1");
    validCharacters.Add("I");
    validCharacters.Add("!");
    validCharacters.Add("2");
    validCharacters.Add("3");
    validCharacters.Add("E");
    validCharacters.Add("4");
    validCharacters.Add("5");
    validCharacters.Add("S");
    validCharacters.Add("6");
    validCharacters.Add("7");
    validCharacters.Add("T");
    validCharacters.Add("8");
    validCharacters.Add("B");
    validCharacters.Add("9");
  • Sayer 2012-06-28 11:18
    DoctorToxn:
    No no no! You just don't get it! He was getting ready for when all the kids grow up and "L33T Speak" is all they can write! This guy was a really forward thinking Brillant Suuuuuuuuuupppperrrrr Geeeeeeeeennniuuuuusssss.


    validCharacters.Add("0");
    validCharacters.Add("O");
    validCharacters.Add("o");
    validCharacters.Add("1");
    validCharacters.Add("I");
    validCharacters.Add("!");
    validCharacters.Add("2");
    validCharacters.Add("3");
    validCharacters.Add("E");
    validCharacters.Add("4");
    validCharacters.Add("5");
    validCharacters.Add("S");
    validCharacters.Add("6");
    validCharacters.Add("7");
    validCharacters.Add("T");
    validCharacters.Add("8");
    validCharacters.Add("B");
    validCharacters.Add("9");


    I get the joke but does "L33T Speak" even exist outside of ridicule anymore?

    persto: too fast to check splelign
  • Quietust 2012-06-28 11:47
    Alex:
    ... if ((c < '0') || (c > '9')) ...

    That only works if your character set happens to put the digits 0-9 in consecutive code points.

    To be fair, this is true for pretty much everything, but trying to do the same logic with 'a' thru 'z' could fail horribly if EBCDIC got involved...
  • DigCamara 2012-06-28 11:49
    Damn those futurians and their weird maths!
  • Peter Orbers 2012-06-28 11:49
    - Uses an array instead of c >= '0' and c <= '9'

    This depends on an arbitrary sort order.
  • Double-Posting Guy 2012-06-28 12:01
    At what time does Alex post articles on this so-called "daily" site?
  • Double-Posting Guy 2012-06-28 12:01
    At what time does Alex post articles on this so-called "daily" site?
  • Christian 2012-06-28 12:12
    There is a wheel that once, a long and long forgotten time ago, was invented and they called it Regex. It was a good wheel and it rolls on to this very day. Programmers like these shun this wheel though as complicated and slow and rather work with wheels that are cut in two, have not less than 3 not more than 5 edges and preferable an axle attached to more than one of these edges. If they didn't invent it, it can't be good.
  • Christian 2012-06-28 12:13
    Double-Posting Guy:
    At what time does Alex post articles on this so-called "daily" site?

    It's more ironic... Like The Daily Show with Jon Stewart.
  • AnonymousCoward 2012-06-28 12:36
    Wouldn't empty strings be accepted too ?
  • PedanticCurmudgeon 2012-06-28 12:37
    Double-Posting Guy:
    At what time does Alex post articles on this so-called "daily" site?
    That reminds me...The "Alex is dead" guy hasn't been seen recently. Is he on vacation or something?
  • not frits at all 2012-06-28 12:41
    Are you saying that the "Alex is dead" guy is dead ?
  • Sarcastic kebab reaper 2012-06-28 13:22
    Imagine this thing is written in PHP
    Half of the comments is about how much PHP sucks.
  • PedanticCurmudgeon 2012-06-28 13:28
    not frits at all:
    Are you saying that the "Alex is dead" guy is dead ?
    I would, but I don't have any creative stories about how he died. Maybe one of the others can assist?
  • Jay 2012-06-28 13:37
    Wow, in that short code snippet, and three different ways to represent true vs false! ("Y"/"N", "1"/"0", and the boolean) 'Hate to get bogged down in consistency or anything.

    Still, it could have been worse. At my last job I worked on a system where the original developers used the strings "true" and "false". I came across a bug once where they had written, if (flag.equals("flase")), i.e. they had a typo spelling "false". As of course "false".equals("flase") is false, false looked like true, with unproductive results.

    The same programmer stored all his numbers as strings, too. When he had to do arithmetic, he converted to Double, did the arithmetic, then converted the result back to a string.
  • qbolec 2012-06-28 13:40
    SG_01:
    return destination.All(x => char.IsNumber(x));

    Is C# really so bad with eta-reduction that you can't simply write:

    return destination.All(char.IsNumber);

    ?

    Anyway, some of you miss that spaces, hash, stars or hypens could be added to the list of legal characters in a phone number at some point in future, and that even O(n*m^2) algorithm is fair enough for n,m < 20, as long as it is easier to write, test, and maintain than O(n) one. But I really doubt this one is one of those.
  • Jay 2012-06-28 13:45
    When I was in school, I was taught that writing


    if (c>='0' && c<='9')


    is wrong. The book said that this relies on the assumption that the character set represents digits with contiguous values, i.e. that if we arranged the characters in order, we wouldn't have letters or punctuation marks interspersed with digits. (This isn't unthinkable. See, "EBCDIC".) The "right" way to do it, the textbook informed us, was to create an array and loop through the elements comparing to each.

    Interesting argument, but it seems to me that any code you write makes assumptions about how the computer works. Putting values in an array assumes that the elements in the array are stored contiguously, so that if I loop through them none will be skipped. It assumes that comparing a character stored in a scalar to a character stored in an array is a valid operation. Etc etc.

    Okay, I'll give that textbook author this: There's a difference between relying on things documented as part of the language spec, and relying on things that could at least theoretically be different if you recompiled the code on a different platform.

  • David 2012-06-28 13:51
    You missed one:
    - Uses substring instead of an indexer
  • Daniel 2012-06-28 15:24
    You danced around the most important fail: it's an O(n^2) solution that could easily be solved in linear time. Most of the other WTFs in that code stem from that problem.
  • Daniel 2012-06-28 15:27
    Blegh, forgot that both loops aren't working on the same set, so it's actually O(nm), and since the valid character array is a constant size, it technically simplifies to O(n), but it's still extremely inefficient.
  • AGray 2012-06-28 15:57
    PedanticCurmudgeon:
    not frits at all:
    Are you saying that the "Alex is dead" guy is dead ?
    I would, but I don't have any creative stories about how he died. Maybe one of the others can assist?


    Toothbrushing accident.

    These things happen...

    CAPTCHA: praesent - It's not a present.
  • Zylon 2012-06-28 16:52
    I hereby rechristen this site "The Demiweekly WTF".
  • Friedrice the Great 2012-06-28 17:22
    PedanticCurmudgeon:
    not frits at all:
    Are you saying that the "Alex is dead" guy is dead ?
    I would, but I don't have any creative stories about how he died. Maybe one of the others can assist?


    Well, turns out that the Alex is Dead guy was really a particular Flame infestation on one of the computers in the DailyWTF office. Then a Flame command system sent the instruction to delete itself ...
  • Enterprise Coder 2012-06-28 21:33
    @Deprecated:
    Wow, so many inefficiencies I don't even know where to start!

    - Rebuilds array every time it is called


    Which is fine if it's only called occasionally and reduces the number of globals cluttering the library.


    - Uses an array instead of c >= '0' and c <= '9'


    Some systems may have to deal with EBCIDC, so you can't just assume numbers are in order.


    - Calls substring repeatedly in inner loops


    What's wrong with that? Small objects are efficiently handled by garbage collection, and substring with a fixed length is a constant time function.


    - Does not exit early from outer for loop


    This is clearly a security function, and exiting early would make it vulnerable to side channel attacks.


    - Using strings instead of booleans


    A boolean requires one word... a reference to a literal string requires one word. How is a boolean less efficient?
  • Brian 2012-06-28 23:06
    private static bool ValidateLinq(string str) { return str.All(x => '0' <= x && x <= '9'); }


    I was surprised that this was quite THAT slow. I know it's not exactly cheap to do the invocation of an anonymous function (which is, iirc, what the lambda gets turned into), but that seems extra slow.

    Maybe using Any() with a negated condition would allow for early exit and speed it up a little?

    Captcha: facilisi. Underwater sealab.
  • Mathlete 2012-06-29 00:15
    Brian:
    private static bool ValidateLinq(string str) { return str.All(x => '0' <= x && x <= '9'); }


    I was surprised that this was quite THAT slow. I know it's not exactly cheap to do the invocation of an anonymous function (which is, iirc, what the lambda gets turned into), but that seems extra slow.

    Maybe using Any() with a negated condition would allow for early exit and speed it up a little?

    Captcha: facilisi. Underwater sealab.


    I tried both an the execution times are about the same. FWIW, both Any and All will early exit (as will the regex versions), as can be seen by putting the invalid characters towards the beginning of the string instead of the end:


    public static void Main(string[] args)
    {
    const string valid = "193485923905820394029850298402983409284032840238402984";
    const string invalidEnd = "193485923905820394029850298402983409284032840238402984a";
    const string invalidStart = "34a534534503985039845038450394850394850398503498503985";

    foreach (var func in new Func<string, bool>[] { ValidateLinqAll, ValidateLinqAny, ValidateRegex, ValidatePrecompiledRegex, ValidateForLoop })
    {
    var startTime = DateTime.Now;
    for (var i = 0; i < 1000000; i++)
    {
    func(valid);
    }
    var endTime = DateTime.Now;
    Console.Out.WriteLine(func.Method.Name + " valid: " + endTime.Subtract(startTime).TotalMilliseconds);

    startTime = DateTime.Now;
    for (var i = 0; i < 1000000; i++)
    {
    func(invalidEnd);
    }
    endTime = DateTime.Now;
    Console.Out.WriteLine(func.Method.Name + " invalid: " + endTime.Subtract(startTime).TotalMilliseconds);

    startTime = DateTime.Now;
    for (var i = 0; i < 1000000; i++)
    {
    func(invalidStart);
    }
    endTime = DateTime.Now;
    Console.Out.WriteLine(func.Method.Name + " w/ early exit: " + endTime.Subtract(startTime).TotalMilliseconds);
    }

    Console.In.ReadLine();
    }

    private static bool ValidateLinqAll(string str) { return str.All(x => '0' <= x && x <= '9'); }
    private static bool ValidateLinqAny(string str) { return !str.Any(x => x < '0' || x > '9'); }
    private static bool ValidateRegex(string str) { return Regex.IsMatch(str, @"^\d*$"); }

    private static readonly Regex ValidatorRegex = new Regex(@"^\d*$");
    private static bool ValidatePrecompiledRegex(string str) { return ValidatorRegex.IsMatch(str); }

    private static bool ValidateForLoop(string str)
    {
    foreach (var c in str) if (c < '0' || c > '9') return false;
    return true;
    }


    Results:
    ValidateLinqAll valid: 613.0613
    ValidateLinqAll invalid: 620.062
    ValidateLinqAll w/ early exit: 64.0064
    ValidateLinqAny valid: 603.0603
    ValidateLinqAny invalid: 630.063
    ValidateLinqAny w/ early exit: 66.0066
    ValidateRegex valid: 2362.2362
    ValidateRegex invalid: 3833.3833
    ValidateRegex w/ early exit: 788.0788
    ValidatePrecompiledRegex valid: 1982.1982
    ValidatePrecompiledRegex invalid: 3442.3442
    ValidatePrecompiledRegex w/ early exit: 403.0403
    ValidateForLoop valid: 85.0085
    ValidateForLoop invalid: 86.0086
    ValidateForLoop w/ early exit: 11.0011
  • Coyne 2012-06-29 00:58
    This is great! I'm gonna run right out and make a StringyString class!
  • hikari 2012-06-29 04:55
    Steve The Cynic:
    RaceProUK:
    emaN ruoY:
    First, as stated, sometimes RegEx really is the answer.

    Assuming the code is .NET, I think Int32.TryParse would be quicker.

    Nice try, but you need to exclude strings beginning with "-" in some way, as TryParse would presumably say that e.g. "-456" is valid...


    Because checking the output of TryParse to see if it's negative is so complicated...

    Either int.TryParse() or long.TryParse() was my first thought too; you could always use a lazy loop over the string and use the char.IsDigit() or char.IsNumber() methods, depending on what you were actually trying to achieve (IsDigit() checks that the character is strictly a radix-10 digit, IsNumber() checks whether the character is classified by Unicode as a number).
  • BenJoe 2012-06-29 06:11
    Public Function IsValid(value as string) as boolean
    Return IsNumeric(value)
    End Function

    There, VB.NET fixed it :P


    PS: I Know The Wrapping Function is kinda obsolete, but this way it gives more Context here ;)
  • LarryDavid 2012-06-29 07:48
    Having recently worked with a company providing this kind of service ... it is unsurprising...
  • Pero Perić 2012-06-29 07:56
    Jay:
    ... Putting values in an array assumes that the elements in the array are stored contiguously, so that if I loop through them none will be skipped. ...

    If by array you mean true array, T[] thingy, than coder has control over where elements are "added" and only assumption is that array filling code works correctly. On the other hand, if by array you mean List<T> than you are talking about interfaces and contracts. List<T> may store elements in any way it sees fit but methods and indexers that expose those elements must work the docs says and as you said, in that case assumption is that docs are reliable.

    This comment assumes that we talk about C# and .Net :)

    captcha: validus - your argument is invalidus
  • TheLurker 2012-06-29 09:41
    Ahhh, should've used MUMPS.
    It'd be a one liner..

    ; If there's anything left over it's not an integer.
    I $L($TR(DEST, "0123456789")) > 0

    I'll get my coat...
  • Slugart 2012-06-29 10:03
    Or they decide to start accepting hex...
  • sagaciter 2012-06-29 11:25
    What? No frist idiots any more? Looks like I cleaned this place of them.
  • mp 2012-06-29 11:36
    - Writes any of this when matching against "^[0-9]*$" would do?
  • blagh 2012-06-29 21:49
    Ugh. Maybe the array is used in case sometime in the future, a new number is added between '4' and '5'.


    Well, yeah, you wanna make sure that if there's ever a need to accept numbers after the decimal point, you can add those in too.
  • Benjamin Howarth 2012-06-30 06:15
    Here's the super-duper-timesaving method of doing this exact same thing (I'm assuming C# here):

    private string checkChars(string destination) {
    return (destination.ToCharArray().All(d => Char.IsNumeric(d)));
    }

    You're welcome.
  • drobnox 2012-07-02 13:07

    public static bool IsNumeric(this string s)
    {
    return s.All(c => Char.IsNumber(c));
    }

  • Todd 2012-07-02 14:40
    Looks like C#, so wow, how about just

    function ContainsOnlyNumbers(string input) {
    foreach(var s in input) {
    if (!Char.IsNumber(s)) { return false; }
    }
    return true;
    }

    Quits ASAP and uses presumably fast built-in functions. Alternatively a reg-ex that only accepts numbers should be quite smart.
  • Jenda 2012-07-04 17:36
    Zmee:
    Just wow! And replacing this with a single line:
    return java.util.regex.Pattern.matches("^\\d*$", destination);

    (And yes, it is d* rather than d+; there is no requirement for the string to be non-empty.)

    Well if this has changed to a code golf ...

    return $destination =~ /^\d*$/;

    or rather the whole sub

    sub checkChars {
    $_[0] =~ /^\d*$/;
    }

    Not that anyone would bother making a function for anything as trivial as this.
  • MyWay 2012-07-05 07:12

    public bool checkChar(string destination)
    {
    int p;
    for(int i = 0; i<destination.Length;i++)
    {
    if (!int.TryParse(destination.Substring(i, 1),out p))
    {
    return false;
    }
    }
    return true;
    }
  • Ben 2012-07-06 02:01
    I think it's just the function name that's misleading. Should have been checkCharsAndSpinWait
  • deleto 2012-07-08 14:30
    Looks like Martin should have no difficulty achieving some stunning performance gains, if management even cares.
  • Fūzetsu 2012-07-11 13:31
    Hah, you would be surprised…

    http://www.scp-wiki.net/scp-033
  • Vince 2012-07-13 16:23
    Hello,

    It is probably an entry for an obfuscation contest ? ;-)

    Never heard of isInt() ?

  • Bozo 2012-07-16 13:20
    Well here's a place to start:

    - apparently unaware that character has an isDigit function.
    - apparently unaware that Java has a regex package. People sometimes gripe about the performance of it, but if it's replacing the code above it can't help being an improvement.
  • Craig 2012-07-26 13:05
    @Deprecated:


    Wait, WTF???
    bool validChars = true;
    and then 4 lines later:
    string matchedChar = "N";


    This is what happens when bad programmer writes ann ill-conceived implementation that doesn't even work, and competent programmer just simply gets it working by throwing in the validChars boolean.

    Alas the business mindset is to "don't touch it now that it's working". I really do wish that weren't the case, because this seriously should have been overhauled.

    Addmittedly, fixing the return type could prove to be a lot more work because who knows how many times the bad programmer has called his Frankenstein.