1

So i have a string S consisting of N letters 'a' or 'b'. This should return 1 if all occurrences of A are before all occurrences of b and return 0 otherwise.

B does not need to occur in S and A does not need to occur in S

For example

S='aabbb' returns 1 
S = 'ba' returns 0
S = 'aaa' returns 1
S= 'b' returns 1

So my approach was to use a for loop on the string and check if b occurs before a or not like so:

char newstr[10] = "aabbba"; //should return 0


int len = strlen(newstr);

for (int i = 0; i < len+1; i++) {
    printf("%c", newstr[i]);
    if (newstr[i] < 'b') {
        printf("1");
    }
    else {
        printf("0");
    }

}

Output is a1a1b0b0b0a1 1 So..it is partially detecting if a is before b but not to its fully correct manner.

ScuffedCoder
  • 376
  • 1
  • 5
  • 21

2 Answers2

7

i have a string S consisting of N letters 'a' or 'b'

should return 1 if all occurrences of A are before all occurrences of b and return 0 otherwise.

So string is not allowed to have a sequence ba inside. So just:

if (strstr(newstr, "ba") == NULL) { printf("1\n"); } else { printf("0\n"); }

or just:

printf("%d\n", !strstr(newstr, "ba"));
KamilCuk
  • 120,984
  • 8
  • 59
  • 111
1

Your code is simply detecting a without checking the relationship with b.

The condition "This should return 1 if all occurrences of A are before all occurrences of b and return 0 otherwise." can be said as "This should return 0 if some occurrences of A are after some occurrences of b and return 1 otherwise.".

An example implementation of this is:

char newstr[10] = "aabbba";

int b_found = 0;
int result = 1;
for (int i = 0; newstr[i] != '\0'; i++) {
    if (newstr[i] == 'b') {
        b_found = 1;
    } else if(b_found && newstr[i] == 'a') {
        /* 'a' is found after 'b' */
        result = 0;
    }
}
printf("%d", result);
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • I see, but if we were to say have a method name with a paramater of a pointer `char *S`. Would I need to get the length of the char using `strlen(*S)` and then setting`char newstr[lengthOfChar] = *S` ? I'm confused on making a more general function. – ScuffedCoder Oct 05 '20 at 13:55
  • 1
    No. `strlen(*S)` will lead to Segmentation fault and `char newstr[lengthOfChar] = *S` will lead to compile error. You can simply delete `char newstr[10] = "aabbba";`, replace all `newstr` to `S`, and use `S[i] != '\0'` to check if you dealt until the end of string. – MikeCAT Oct 05 '20 at 13:58