nexus/text.c

103 lines
2.0 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "defs.h"
#include "objects.h"
char *capitalise(char *text) {
text[0] = toupper(text[0]);
return text;
}
int isvowel (char c) {
switch (c) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
return B_TRUE;
}
return B_FALSE;
}
// allocates and returns new string
char *makeplural(char *text) {
int newlen;
char lastlet;
char *newtext;
char *p;
int rv;
newtext = strdup(text);
// scrolls
rv = strrep(newtext, "scroll ", "scrolls ");
if (rv) return newtext;
rv = strrep(newtext, "potion ", "potions ");
if (rv) return newtext;
rv = strrep(newtext, "piece ", "pieces ");
if (rv) return newtext;
rv = strrep(newtext, "pair ", "pairs ");
// don't return
// default
lastlet = text[strlen(text)-1];
switch (lastlet) {
case 's':
case 'o': // append "es"
asprintf(&newtext, "%ses",text);
break;
default: // append "s"
asprintf(&newtext, "%ss",text);
break;
}
return newtext;
}
int strrep(char *text, char *oldtok, char *newtok) {
char *temp;
int rv;
temp = strdup(" ");
rv = dostrrep(text, &temp, oldtok, newtok);
// swap
text = realloc(text, strlen(temp));
strcpy(text, temp);
free(temp);
return rv;
}
// returns TRUE if any replacements made
int dostrrep(char* in, char** out, char* oldtok, char* newtok) {
char *temp;
char *found = strstr(in, oldtok);
int idx;
if(!found) {
*out = realloc(*out, strlen(in) + 1);
strcpy(*out, in);
return B_FALSE;
}
idx = found - in;
*out = realloc(*out, strlen(in) - strlen(oldtok) + strlen(newtok) + 1);
strncpy(*out, in, idx);
strcpy(*out + idx, newtok);
strcpy(*out + idx + strlen(newtok), in + idx + strlen(oldtok));
temp = malloc(idx+strlen(newtok)+1);
strncpy(temp,*out,idx+strlen(newtok));
temp[idx + strlen(newtok)] = '\0';
dostrrep(found + strlen(oldtok), out, oldtok, newtok);
temp = realloc(temp, strlen(temp) + strlen(*out) + 1);
strcat(temp,*out);
free(*out);
*out = temp;
return B_TRUE;
}