有没有人能帮我实现这两道题啊,感激涕零
1,将用户输入的字符串,按相反的次序存放在数组中;2,编写程序直接实现strcmp()函数功能的代码
#include <iostream> using namespace std; #include <string> int main(){ string s1, s2; // Promote user to input cout << "输入字符串:" << endl; cin >> s1; int len = s1.size(); //cout << len << endl; for(int i = len; i > 0; i--) s2[len - i] = s1[i - 1]; //反序输出 for(int j = 0; j < len; j++) cout << s2[j]; system("pause"); return 0; }
#include <iostream> using namespace std; void reverse(char *s){ int n = strlen(s); char c; for (int i = 0;i < n/2;++i){ c = s[i]; s[i] = s[n-1-i]; s[n-1-i] = c; } } int my_strcmp(const char *s1,const char *s2){ for (int i = 0;s1[i] != '\0' && s2[i] != '\0';++i){ if (s1[i] == s2[i]) continue; else if (s1[i] > s2[i]) return 1; else return -1; } if (s1[i] != '\0') return 1; else if (s2[i] != '\0') return -1; else return 0; } int main() { //testing my_strcmp const char *s1 = "a string"; const char *s2 = "A string"; int i = my_strcmp(s1,s2); cout << i << endl; //testing reverse char str[100]; cin >> str; reverse(str); cout << str << endl; return 0; }