Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <stdbool.h>
- bool speechmarkArg(char* str, char** args, int* index, int* argCount) {
- static const char key[] = {"\""};
- int length = strlen(str);
- // increment index to point to the first character of the argument
- *index += 1;
- // get the length of the argument
- int argLength = strcspn(str + (*index), key);
- // no closing speechmark was found, return an error
- if ((*index + argLength) == length) {
- return false;
- }
- // store the new argument in the array of arguments
- args[*argCount] = malloc((argLength + 1) * sizeof(char));
- memcpy(args[*argCount], str + (*index), argLength);
- strcat(args[*argCount], "\0");
- // update index to point to the closing speechmark. Upon returning
- // to the splut function, the for loop will immediately cycle past
- *argCount += 1;
- *index += argLength;
- // return true on success
- return true;
- }
- bool whitespaceArg(char* str, char** args, int* index, int* argCount) {
- static const char key[] = {"\" "};
- char delim;
- // get the length of the argument
- int argLength = strcspn(str + (*index), key);
- // store the delimiting character
- delim = str[*index + argLength];
- // store the new argument in the array of arguments
- args[*argCount] = malloc((argLength + 1) * sizeof(char));
- memcpy(args[*argCount], str + (*index), argLength);
- strcat(args[*argCount], "\0");
- // update the index and argcount
- *index += argLength;
- *argCount += 1;
- if (delim == ' ' || delim == '\0') {
- return true;
- } else {
- if (!speechmarkArg(str, args, index, argCount)) {
- return false;
- }
- }
- // return true on success
- return true;
- }
- int main() {
- char** args = malloc(32 * sizeof(char*));
- char* str = " arg1 arg2\"the best arg\"arg3 \"another great argument\" arg4 arg5 ";
- int length = strlen(str);
- int argCount = 0;
- for (int i = 0; i < length; i += 1) {
- if (str[i] == ' ') {
- continue;
- } else if (str[i] == '\"') {
- if (!speechmarkArg(str, args, &i, &argCount)) {
- puts("error: expected closing quotation mark");
- break;
- }
- } else {
- if (!whitespaceArg(str, args, &i, &argCount)) {
- puts("error: expected closing quotation mark");
- break;
- }
- }
- }
- // probably wanna free here tbh
- // keep track of the fact the arguments weren't successfully closed
- for (int i = 0; i < argCount; i += 1) {
- puts(args[i]);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement