Help make the program in C.

A1 = {A,B,C,D,E,F,G,H,I,J}; A2 = {0,1,2,3,4,5,6,7,8,9}; 

The function replaces the characters of a string from one given alphabet with the characters of another alphabet.

  • 2
    did you try to do anything yourself, or do you want everyone to do it for you? - DreamChild
  • one
    Well ... find the element in the first array, substitute the element of the second with the same number instead ... - Zelta
  • @Zelta, try to understand this and this examples. Or write some "associative array" in C. - avp
  • one
    @avp Well, you really do not scare. For eight-bit characters, the code conversion table is char a1a2 [256]; bzero (a1a2, 256); for (i = 0; i <sizeof A1; i ++) a1a2 [A1 [i]] = A2 [i]; a1a2 [''] = ''; a1a2 ['\ n'] = '\ n'; And you are afraid of associative arrays. PS: do not forget about the sign only during transcoding, a1a2[(unsigned char) c] - alexlz
  • Of course, I frighten, warning the shock of Unicode (more specifically from Russian letters in UTF-8). And for a byte- bzero() IMHO, instead of bzero() , it is better to initialize with the codes themselves: for (i = 0; i <256; i ++) a1a2 [i] = i; for (i = 0; i <sizeof A1; i ++) a1a2 [A1 [i]] = A2 [i]; then the further code conversion code will be completely trivial. - avp

1 answer 1

@atticus so?

 #include <iostream> using namespace std; int main() { string s; while(!cin.eof()) { cin >> s; for(string::iterator it = s.begin(); it!=s.end(); it++) { if(*it < 'A' || *it > 'J') { cout << "Неверный символ " << *it << endl; return 0; } *it -= 'A' - '0'; } cout << s; } return 0; } 
  • Yes, that's right. Many thanks. - atticus
  • 3
    @atticus was a joke. First, there are no arrays (according to the conditions of the problem they should be like). The second is the relation of the program to spaces / line breaks (they are discarded). - alexlz
  • @alexlz: Why a joke? A good optimizing compiler could easily turn an array search into code like yours. (expand the loop through the array -> substitute constants -> make a table of values ​​-> collapse it into an expression) - VladD
  • 2
    Recall Stanislavsky and his favorite phrase "I do not believe!" - alexlz
  • 3
    Well, look. 1. for (int i = 0; i < 10; i++) if (x == a[i]) return b[i] -> if (x == a[0]) return b[0]; if (x == a[1]) return b[1]; ... if (x == a[0]) return b[0]; if (x == a[1]) return b[1]; ... if (x == a[0]) return b[0]; if (x == a[1]) return b[1]; ... 2. if (x == a[0]) -> if (x == 'A') 3. if 's sequence -> switch 4. Minimize the range to switch (default optimization in Java, for example): if (arg outside range) default; else jump table[arg] if (arg outside range) default; else jump table[arg] 5. inline case'y 6. we take out the general subexpression for jump 7. we see that now all cases are the same, and we collapse them. - VladD