vc++相关程序问题以及其面向对象程序设计初步实践相关问题……
运行结果及代码如下:
#include <iostream>
using namespace std;
class String
{
private:
char* str;
int len;
public:
String(const char* ptr)
{
int i = 0;
while (ptr[i] != '\0')
i++;
len = i;
str = new char[len + 1];
i = 0;
while (ptr[i] != '\0')
{
str[i] = ptr[i];
i++;
}
str[i] = 0;//结尾
}
char getc(int n)
{
if (n > 0 && n <= len)
return str[n - 1];
else
return 0;
}
void setc(int n, char c)
{
if (n > 0 && n <= len)
str[n-1] = c;
}
void setlen()
{
int i = 0;
if (str == 0)
{
len = 0;
return;
}
while (str[i])
i++;
len = i;
}
void show()
{
if (str)
cout << str << endl;
else
cout << "字符串为空" << endl;
}
~String()
{
if (str)
{
delete[] str;
str = 0;
}
}
};
int main()
{
char buf[100], c;
cout << "请输入一个字符串:";
cin >> buf;
String s(buf);
int n;
cout << "获取第n个字符,请输入n:";
cin >> n;
cout << "第" << n << "个字符是:" << s.getc(n) << endl;
cout << "设置第n个字符,请输入n和字符:";
cin >> n >> c;
s.setc(n, c);
cout << "字符串为:";
s.show();
return 0;
}
#include <iostream>
#include <string.h>
using namespace std;
class String
{
private:
char *str;
int len;
public:
String(const char *ptr){
if (!ptr)
{
str = new char[1];
*str = '\0';
}
else
{
int nLen = strlen(ptr);
str = new char[nLen + 1];
strcpy(str, ptr);
}
}
~String ()
{
if(str != NULL)
free(str);
}
char getc(int n){
return str[n];
}
void setc(int n,char c){
str[n]=c;
}
void setlen(){
len=strlen(str);
}
void show(){
printf("字符串内容:%s,字符串长度:%d",str,len);
}
};
int main(){
String sss("abcdef");
printf("%c\n",sss.getc(2));
sss.setc(2,'d');
sss.setlen();
sss.show();
return 0;
}
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!