#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
typedef int (* fptrOperation)(const char *, const char *);
char *returnALiteral(int);
size_t stringLength(const char *str);
char *format(char *, size_t, const char*, size_t, size_t);
int compare(const char*, const char*);
int compareIgnoreCase(const char*, const char*);
char* stringToLower(const char *);
void bubleSort(char* [], size_t, fptrOperation);
int main(int argc, char *argv[])
{
char simpleArray[] = "simple string";
char *simplePtr = (char*)malloc(strlen("simple string")+1);
strcpy(simplePtr, "simple string");
printf("%d\n",stringLength(simpleArray));
//printf("%d\n",stringLength(&simpleArray));
printf("%d\n",stringLength(&simpleArray[0]));
char *buffer = (char *)malloc(100);
printf("%s\n", format(buffer, 100, "Alex", 30, 50));
printf("test for argv\n");
for (int i = 0; i < argc; i++) {
printf("argv[%d]: %s\n", i, *argv++);
}
char* names[] = {"Bob", "Ted", "Carol", "Alice", "alice"};
printf("%d\n", sizeof(names));
bubleSort(names, 5, compareIgnoreCase);
for (int i = 0; i < 5; i++) {
printf("%s ", *(names + i));
}
return 0;
}
size_t stringLength(const char *str) {
size_t len = 0;
while (*str++)
len++;
return len;
}
char *format(char *buffer, size_t size, const char * name, size_t quantity, size_t weight) {
snprintf(buffer, size, "Item: %s Quantity: %u Weight: %u", name, quantity, weight);
return buffer;
}
char* returnALiteral(int code) {
switch(code) {
case 100:
return "Boston Processing Center";
case 200:
return "Denver Processing Center";
case 300:
return "Atlanta Processing Center";
case 400:
return "San Jose Processing Center";
}
}
int compare(const char *s1, const char*s2) {
return strcmp(s1, s2);
}
int compareIgnoreCase(const char *s1, const char *s2) {
char *temp1 = stringToLower(s1);
char *temp2 = stringToLower(s2);
int result = strcmp(temp1, temp2);
free(temp1);
free(temp2);
return result;
}
char* stringToLower(const char * str) {
char *temp = (char *)malloc(strlen(str) + 1);
char *start = temp;
while (*start++ = tolower(*str++))
;
return temp;
}
void bubleSort(char* arr[],size_t size, fptrOperation operation) {
int swap = 1;
while (swap) {
swap = 0;
for (size_t i = 0; i < size - 1; i++) {
if (operation(arr[i], arr[i+1]) > 0) {
swap = 1;
char *temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
}
}
}
}
C pointers and string
最新推荐文章于 2020-05-23 15:57:58 发布