refactor remove $ symbol

This commit is contained in:
Chris Cromer 2021-07-17 21:22:03 -04:00
parent daa9cf8673
commit 8f57501927
2 changed files with 23 additions and 22 deletions

View File

@ -126,17 +126,7 @@ void set_variable(StringArray *args) {
return; return;
} }
char *variable = malloc((strlen(args->array[1])) * sizeof(char *)); char *variable = remove_variable_symbol(args->array[1]);
if (variable == NULL) {
perror("malloc");
exit(EXIT_FAILURE);
}
memset(variable, 0, strlen(args->array[1]));
// Remove the $ symbol from the string
for (size_t i = 0; i < strlen(args->array[1]); i++) {
variable[i] = args->array[1][i + 1];
}
// Check variable name for invalid characters // Check variable name for invalid characters
for (size_t i = 0; i < strlen(variable); i++) { for (size_t i = 0; i < strlen(variable); i++) {
@ -196,17 +186,7 @@ void echo(StringArray *args) {
for (size_t i = 1; i < args->size; i++) { for (size_t i = 1; i < args->size; i++) {
if (args->array[i][0] == '$') { if (args->array[i][0] == '$') {
char *variable = malloc((strlen(args->array[i])) * sizeof(char *)); char *variable = remove_variable_symbol(args->array[i]);
if (variable == NULL) {
perror("malloc");
exit(EXIT_FAILURE);
}
memset(variable, 0, strlen(args->array[i]));
// Remove the $ symbol
for (size_t j = 0; j < strlen(args->array[i]); j++) {
variable[j] = args->array[i][j + 1];
}
char *value = get_array_list(variables, variable); char *value = get_array_list(variables, variable);
if (value == NULL) { if (value == NULL) {
@ -239,3 +219,17 @@ void echo(StringArray *args) {
} }
free_string_array(no_variables); free_string_array(no_variables);
} }
char *remove_variable_symbol(char *original_variable) {
char *variable = malloc((strlen(original_variable)) * sizeof(char *));
if (variable == NULL) {
perror("malloc");
exit(EXIT_FAILURE);
}
memset(variable, 0, strlen(original_variable));
for (size_t i = 0; i < strlen(original_variable); i++) {
variable[i] = original_variable[i + 1];
}
return variable;
}

View File

@ -62,4 +62,11 @@ void set_variable(StringArray *args);
*/ */
void echo(StringArray *args); void echo(StringArray *args);
/**
* Remove the $ symbol from a variable name.
* @param original_variable The original variable name.
* @return Returns the string without the $ symbool.
*/
char *remove_variable_symbol(char *original_variable);
#endif #endif