Code:
#include<stdio.h>
#define MAXL 256
// funcoes pos e inv
int mystrlen(char *string) { // My String Lenght - returns string lenght
int len = 0;
while(*(string+len)!='\0') {
len++;
}
return len;
}
char* inv(char* C) { // REVERSE C and returns C reversed
int length, i;
char *begin;
char *end;
char temp;
length = mystrlen(C);
begin = C;
end = C;
end += length-1;
for (i=0;i<length/2;i++) {
temp = *end;
*end = *begin;
*begin = temp;
begin++;
end--;
}
return C;
}
char* pos(char* C,char* S) { // FIND C in S and returns a pointer for a char that contains the positions where C is in S
int CAux = 0; int csize = mystrlen(C);
int SAux = 0; int ssize = mystrlen(S);
int howMany = 1;
char results[ssize];
char* r = results;
int i;
for(i=0;i<ssize;i++){
if(C[CAux] == S[i]){
SAux = i;
while((C[CAux]==S[SAux]) && (CAux<(csize-1))){
CAux++;
SAux++;
howMany++;
if(howMany == (csize-1)){
sprintf(results + mystrlen(results), " %d", i);
}
}
SAux = i + 1;
CAux = 0;
howMany = 0;
}
}
return r;
}
/* _-*_-*_-*_-*_-* MAIN *-_*-_*-_*-_*-_ */
int main(int argc, char *argv[]) {
char str[MAXL];
char *r=str;
// declarar aqui outras variaveis, se necessario (another var.)
char *compStr;
char* res;
while(r!=NULL) {
r=fgets(str,MAXL,stdin);
// chamar a funcao pos() ou inv(), conforme o caso (call pos() or inv())
if(argv[1][0] == 'p') { // pos()
compStr = argv[2];
res = pos(compStr, r);
}
else if(argv[1][0] == 'i') { // inv()
res = inv(r);
}
// imprimir os resultados (Print results)
printf("%s\n",res);
}
return 0;
}
on running this program:
1 ____ "i"
if you do ./cadeias i: (inv function that reverses C)
you will able to write a string to return the reverse.
ex: ./cadeias i (enter)
Pedro
out -> ordeP
2 _____ "p"
if you do ./cadeias p anystring: (pos function that finds C in S)
you will be able to write a sting to find in "anystring" and returns the posicions that the sub string are.
ex: ./cadeias p PETER
E
out -> 2 4
but, its printing things like that: "pYS�����"
can you help me finding where is the problem???