注册 登录
编程论坛 C++教室

有没有人能帮我实现这两道题啊,感激涕零

yqfang310 发布于 2008-03-05 15:52, 818 次点击
1,将用户输入的字符串,按相反的次序存放在数组中;
2,编写程序直接实现strcmp()函数功能的代码
5 回复
#2
Waiting1592008-03-05 20:38
程序代码:
#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;
}
#3
yqfang3102008-03-06 15:50
谢谢啦
#4
sunkaidong2008-03-06 16:03
反续:
#include <iostream>
using namespace std;
#include <string>
class string1:public string
{
public:
    string1 &operator~()
    {   string1 s2;
        for(int i=(*this).size()-1;i>=0;i--)
    {
        s2+=*((*this).c_str()+i);
    }
        *this=s2;
        return *this;
    };
};
int main(){
    string1 s1,s;   
    cout << "输入字符串s1:" << endl;
    s1.c_str();
    cin >> s1;
    cout << "输出字符串s1:" << endl;
    cout<<~s1<< endl;    
    system("pause");
    return 0;
}
#5
aipb20072008-03-06 20:06
程序代码:
#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;
}
#6
aipb20072008-03-06 20:32
strcmp那样写好理解,其实2,3行就可以解决
1