I wrote a program that inputs a string with spaces between them and should allocate a new string with only 1 space between the words. and I was wondering if there’s a better way to write it ( I rewrote it a couple of times and I’m trying to find the most effective way to write this code) anyway this is it:
#define _CRT_SECURE_NO_WARNINGS #define SIZE 80 #include <stdio.h> #include <string.h> #include <stdlib.h> char* UpgradeString(char* oldText); void inputStr(char* str); int main() { char str[SIZE], *ans; printf("Enter string\n"); inputStr(str); ans = UpgradeString(str); puts(ans); } void inputStr(char* str) { int i = 0; fgets(str, SIZE - 1, stdin); while (str[i] != '\n')i++; str[i] = 0; } char* UpgradeString(char* oldText) { char temp[SIZE], *ans; int i=0, k = 0; while (1) { if (oldText[i] == 0)break; if (oldText[i] != ' ') { temp[k] = oldText[i]; k++; } if (oldText[i] == ' '&&(oldText[i + 1] != ' '&&oldText[i + 1] != 0)) { temp[k] = oldText[i]; k++; } if (oldText[i] == ' ')i++; else i++; } temp[k] = 0; ans = (char*)malloc(sizeof(char)*(strlen(temp) + 1)); strcpy(ans, temp); return ans; }
thanks for the help!