Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: String functions without string.h library

Tags:

c

string

I have homework to do and I need some help. I didn't come here to get someone to do my work, just to help me.

I have to create my own string.h "library" (actually header and function file), so I am forbidden to use #include <string.h> and #include <ctypes.h>. They also recommended us not to use malloc, but it was just a recommendation, not forbidden. For most of the functions I know how to write them. I planned to save "strings" like arrays of chars like:

char array[50];

But I came to a problem of creating toupper and tolower functions. Sure, I can make huge switch cases or a lot if (else if's) like this:

if(string[i]=='a') {string[i]=='A' };
 else if(string[i]=='b') {string[i]=='B' };
    .
    .
    .
    else if(string[i]=='z') {string[i]=='Z' };

But is there any better solution?

Strings are going to be created randomly so they will look somewhat like this:

ThisISSomESTRing123.

So after toupper function, randomly generated string should look like this:

THISISSOMESTRING123.

Also how would you create puts function (printing) so everything would be in same row? Just "printf" inside "for" loop?

like image 250
Matej Veličan Avatar asked Dec 06 '22 21:12

Matej Veličan


2 Answers

Your system probably uses ASCII. In ASCII, the codepoints of lowercase characters and uppercase characters are sequential.

So we can just do:

void to_upper(char *message) {
    while (*message) {
        if (*message >= 'a' && *message <= 'z')
            *message = *message - 'a' + 'A';
        message++;
    }   
}   

Other character encodings can become much more complicated. For example, EBCDIC doesn't have contiguous characters. And UTF-8 introduces a world of problems because of the numerous languages that you need to support.

like image 191
Bill Lynch Avatar answered Dec 31 '22 02:12

Bill Lynch


You can just check if the character is within the range of characters, say between 'a' and 'z' and just add or subtract 32, which is the difference between the ascii value of capital and lower letters. See the ascii table here: http://www.asciitable.com/

like image 23
rost0031 Avatar answered Dec 31 '22 02:12

rost0031