0

I want to create a function to take a string like this "2014-02-13T06:20:00"

and to convert to a long long int like 20140213062000.

Has anyone a idea how this can be done?

chqrlie
  • 131,814
  • 10
  • 121
  • 189
user1555
  • 23
  • 4
  • 1
    What have you tried? Did it work? Do you know how to for example convert a string `"2014-02"` to `"201402"`? Do you know anything about strings in C? – KamilCuk May 27 '20 at 08:56
  • @KamilCuk I try with strtoll and strtol but the output is only 2014 – user1555 May 27 '20 at 09:07
  • Did you expect `strtol` to convert or omit `-` in the string? What do you think you have to do with the `-` in the input? – KamilCuk May 27 '20 at 09:08

1 Answers1

4

Here is an algorithm, you will just write the code:

  • define a long long variable n and initialize it to 0.
  • for each character c in the string:
    • if c is a digit, ie greater or equal to '0' and less or equal to '9':
    • multiply n by 10 and add the value represented by c, store the result in n.
    • else:
    • ignore the non digit character
  • n should have the expected value.

This would convert positive values. If the string has an initial - indicating a negative number, you would test that and negate the number at the end. Note also that overflowing the range of long long int has undefined behavior with this approach.

Your attempt in the comment needs some improvements:

long long string_To_long(const char sl[]) {
    long long int n = 0;
    for (int i = 0; sl[i] != '\0'; i++) {
        char c = sl[i];
        if (c >= '0' && c <= '9')
            n = n * 10 + (c - '0');
    }
    return n;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
  • Alternatively, parse the string, copy the relevant parts to a temporary string, then call strtoul on that one. `char tmp[14+1] = { [0]=str[0], [1]=str[1], ...}; ... return strtoul(tmp, NULL, 10);` – Lundin May 27 '20 at 09:20
  • @Lundin: this approach requires making an assumption on the string length and format. I would suggest `strtoll` or `strtoull` in this case. – chqrlie May 27 '20 at 10:28
  • @user1555: using an `int` index `i` and a `char *s`, `s[i]` is the n-th character of the string. You would stop the scan when `s[i] == 0`. I suggest getting a real course in C. – chqrlie May 27 '20 at 10:29
  • @user1555 almost there: there is no need to make a copy of the string argument and this `strcpy` would have undefined behavior if that string has more than 18 characters. The digit value is `sk[i] - '0'`, and you must return `n` at the end. – chqrlie May 27 '20 at 10:38