Skip to content

Instantly share code, notes, and snippets.

@WangYihang
Last active May 25, 2021 04:24
Show Gist options
  • Save WangYihang/77ae694e1e75f3fa9840ec3ab96d4f19 to your computer and use it in GitHub Desktop.
Save WangYihang/77ae694e1e75f3fa9840ec3ab96d4f19 to your computer and use it in GitHub Desktop.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
unsigned char upper(unsigned char ch) {
if (ch >= 'a' && ch <= 'z') {
ch ^= 0x20;
}
return ch;
}
unsigned char lower(unsigned char ch) {
if (ch >= 'A' && ch <= 'Z') {
ch ^= 0x20;
}
return ch;
}
unsigned char* str2upper(unsigned char* str, int length) {
unsigned char* dst = (unsigned char*) malloc(length + 1);
for (int i = 0; i < length; i++ ){ dst[i] = upper(str[i]); }
dst[length] = 0;
return dst;
}
unsigned char* str2lower(unsigned char* str, int length) {
unsigned char* dst = (unsigned char*) malloc(length + 1);
for (int i = 0; i < length; i++ ){ dst[i] = lower(str[i]); }
dst[length] = 0;
return dst;
}
void str2upper_test() {
unsigned char* x = "hello wolrd!";
unsigned char* y = str2upper(x, strlen(x));
printf("str2upper('%s') = '%s'\n", x, y);
free(y);
}
void str2lower_test() {
unsigned char* x = "HellO wOlRD!";
unsigned char* y = str2lower(x, strlen(x));
printf("str2lower('%s') = '%s'\n", x, y);
free(y);
}
int main(){
str2upper_test();
str2lower_test();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment