0

I try to run reverse on string But it does not work for me.

For example i tried:-
Run to the letter Z in str and store all the letter that comes between the letter Z and A on a new string str1.

My code:

int main()
{  
    char str[8] = "RREADFZ";
    char str1[8];
    int i,k;

    for(i =0; i<8; i++)
    {
         if(str[i] == 'Z')
         {
                 while(str1[k] != 'A')
                 {
                      str1[k] = str[i];
                      i--;
                      k--;
                 } 
         }
    } 
    printf("%s\n",str1);
}
kevin gomes
  • 1,775
  • 5
  • 22
  • 30
user3313154
  • 3
  • 1
  • 2

2 Answers2

2

You need to initialize k to 0 and increment it in your while loop; k++. At the end you need to store \0 in the array str1.

haccks
  • 104,019
  • 25
  • 176
  • 264
0
#include <stdio.h>
#include <string.h>

int main(){
    char str[8] = "RREADFZ";
    char str1[8] = {0};
    int i, k, aPos, zPos, len = strlen(str);

    aPos = zPos = -1;
    for(i =0; i<len; i++){
        if(str[i] == 'A'){
            aPos = i;
        } else if(str[i] == 'Z'){
            zPos = i;
            break;
        }
    }
    if(aPos != -1 && zPos != -1){
        for(k=0, i=zPos-1;i>aPos;--i,++k){
            str1[k]=str[i];
        }
    }
    printf("%s\n", str1);//FD
    return 0;
}

UPDATE (define function)

#include <stdio.h>
#include <string.h>

void between(char out[], const char in[], char front, char back){
    int i, k, frontPos, backPos, len = strlen(in);
    frontPos = backPos = -1;
    for(i =0; i<len; i++){
        if(in[i] == front){
            frontPos = i;
        } else if(in[i] == back){
            backPos = i;
            break;
        }
    }
    k = 0;
    if(frontPos != -1 && backPos != -1){
        for(i=backPos-1;i>frontPos;--i,++k){
            out[k]=in[i];
        }
    }
    out[k]='\0';
}

int main(){
    char str[] = "RREADFZ";
    char exp[] = "2-3 +5 * 7";
    char cutout[16];

    between(cutout, str, 'A', 'Z');
    printf("str:%s\n", cutout);//FD
    between(cutout, exp, '+', '*');
    printf("exp:%s\n", cutout);// 5

    return 0;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
  • @user3313154 I think the same way and is valid. – BLUEPIXY Feb 16 '14 at 17:23
  • For some reason it does not work for me with the numbers I put this exercise: 2-3 +5 * 7 program running and maintains multiplication sign and back to a plus sign. Did not work you may need to change more than he? – user3313154 Feb 16 '14 at 17:27
  • @user3313154 I think it will work if it means for example that taking out the characters between the + and *.(cut out 5) – BLUEPIXY Feb 16 '14 at 17:58
  • http://stackoverflow.com/a/21800127/971127 this answer extraction of lexical which should be large enough. – BLUEPIXY Feb 16 '14 at 18:19