首页 > 编程开发 > C/C++ > 正文  
标准C程式库--问题例--类型 String
出自:http://home.pchome.com.tw/computer/cpp2000/ 2002年01月20日 14:21
Q1:撰写下列函式,其引数为 string 类别

islower - 引数的内容为小写字母,删传回true
isdigit - 引数的内容为数字,则传回 true
isalphabetic - 引数的内容为大小写字母,则传回 true
isaplhanumeric - 引数的内容为大小写字母或数字时 ,则传回 true

A1:须引入

bool islower(string &text)
{
for (unsigned int i=0;i'z')) return false;
}
return true;
}

bool isdigit(string &text)
{
for (unsigned int i=0;i '9')) return false;
}
return true;
}

bool isaplhabetic(string &text)
{
for (unsigned int i=0;i'Z')) &&
((text[i] 'z'))
) return false;
}
return true;
}

bool isalphanumeric(string &text)
{
for (unsigned int i=0;i'z')) &&
((text[i] 'Z')) &&
((text[i] '9'))
) return false;
}
return true;
}


--------------------------------------------
Q2:撰写一函式可以判断两字串是否为异位字 ( 长度和字母相同,但顺序不同 )。

A2:须引入 、

bool anagram(string s1,string s2)
{
sort(s1.begin(),s1.end()); //将两字串排序,并比较是否相同
sort(s2.begin(),s2.end());
if (s1 == s2) return true;
return false;
}

--------------------------------------------
Q3:从输入流读入一文字档案,并计算单字个数和平均每个字的长度。

A3:须引入 、、
void main()
{

string filename,buffer,word; //宣告变数
fstream file; //buffer 为资料缓区
int words=0,allchar=0; //word 为允许的英文字母
int start,end;

//以下为档案读取程序,此程式没有错误处理
cout > filename;

file.open(filename.c_str());
while (!file.eof()) //读取资料圈
{
char ch;
file.get(ch);
buffer += ch;
}
file.close();

//合法字母填入
for (int i=0;i=0 && start len) end = len; //检查取得值是否正确
allchar += (end-start); //加总字数
words++; //单字数加一
start = buffer.find_first_of(word,end++); //在取得下一个合法字母位置
} //从 end 後的位置开始
double average = double(allchar) / words; //型别转换
cout

class NString : public string
{
public:

NString operator * (unsigned int);
};

NString NString::operator * (unsigned int n)
{
NString temp;
while (n!=0)
{
temp += c_str();
n--;
}
return temp;
}
--------------------------------------------
Q5:以继承的方法,重载 "- " 运算子,使它的功能为--删除特定字串。如果有重的字串,请删除最前的字串。

A5:须引入
class NString : public string
{
public:
NString operator - (NString);
};

NString NString::operator - (NString str)
{
NString temp;
unsigned int pos1 = string::find(str);
unsigned int len1 = str.length();
temp.assign(c_str());
if (pos1 > 0 && pos1
class NString : public string
{
public:
operator int();
};

NString::operator int()
{
string num("0123456789"),temp; //所有合法的数字
int val=0;

//取得第一个数字的位置
unsigned int start = find_first_of(num,0);
unsigned int end = find_first_not_of(num,start);
temp = substr(start,(end-start));

//转换字串成整数
for (unsigned int i=0;i {
val += (temp[i] - '0'); //利用圈来取得每一个字元的数字
val *= 10; //取得後进位,但个位数会移到十位数
} //除 10 把个位数拉回
if ( at(start-1) == '-' ) return -val/10; //数字前一个位置是否为负号
return val/10;
}
--------------------------------------------

】【http://www.trainlinux.com】【Close
『相关资料』
如何在 Linux 中得到特殊键的扫描码? (2002-01-18 14:16)
Glibc 2 HOWTO 中文版 -- 1. 简介 (2002-01-17 14:16)
Glibc 2 HOWTO 中文版 -- 2. 选择你的安装方式 (2002-01-17 14:15)
Glibc 2 HOWTO 中文版 -- 3. 取得函式库 (2002-01-17 14:15)
Home 

诚恩Linux培训工作室