String in C kürzen
-
blindesSmiley schrieb:
dann muß man doch sicher auch noch das strlen() anpassen
stimmt.
Ich hab die Funktion gerade noch so geändert, dass man auch Endungen anhängen kann, die länger sind als die ursprüngliche Endung:
char *replace(char *path, char *ext) { char *ret = strrchr(path, '/'); if (!ret) { ret = path; } ret = strrchr(ret, '.'); if (ret) { int len_ret = strlen(ret); int len_ext = strlen(ext); if (len_ret - 1 < len_ext) { int new = len_ext - len_ret; if ((path = realloc(path, strlen(path) + new)) == '\0') { return 0; } } strcpy(ret + 1, ext); } return path; }
-
wieso les ich das new als variable nur so gerne
evtl. könnte man noch das int in size_t tauschen
-
#include <stdio.h> #include <stdlib.h> #include <string.h> char *replace(char *path, char *ext) { char *ret = strrchr(path, '/'); if (!ret) { ret = path; } ret = strrchr(ret, '.'); if (ret++) { int diff = strlen(ext) - strlen(ret);//buggy? if (diff++ > 0) { if ((path = realloc(path, strlen(path) + diff)) == '\0') { return 0; } } strcpy(ret,ext); } return path; } int main(void) { char *s = malloc(sizeof("/asd.asd/file.xx")); strcat(s,"/asd.asd/file.xx"); printf(replace(s,".nn")); return EXIT_SUCCESS; }
@edit size_t ist unsigned das wird ja nie negativ
-
buggy? könnt schon sein...
int main(void) { size_t a = ~0; int b = 0 - a; printf("%d",b); return 0; }
-
Hallo Leute,
ist ja wahnsinn wie viel auf meine Frage geantwortet wurde. Mit eurer Hilfe habe ich es nun auch problemlos hinbekommen!
Vielen Dank!
Übrigens: auch die allererste Lösung die gepostet wurde funktioniert bei mir.