一、反向打印字符串
1.使用for循环访问字符串
#include <iostream>
#include<string>
int main()
{
using namespace std;
cout << "Enter a word: ";
string word;
cin >> word;
for (int i = word.size() - 1; i >= 0; i--)
{
cout << word[i];
}
return 0;
}
在 C++ 的标准库中,size()
通常是作为容器类(如 std::vector
、std::array
、std::list
等)的成员函数提供的,用来返回容器中元素的数量。
2.调换数组元素
#include <iostream>
#include<string>
int main()
{
using namespace std;
cout << "Enter a word:";
string word;
cin >> word;
char temp;
int i, j;
for (j = 0, i = word.size() - 1; j < i; --i, ++j)
{
temp = word[i];
word[i] = word[j];
word[j] = temp;
}
cout << word << endl;
}
二、递增/递减运算符与指针
#include <iostream>
using namespace std;
int main()
{
double arr[5] = { 21.1,33.8,47.9,56.7,80.0 };
double *pt = arr;
cout << pt << endl;
cout << ++pt << endl;;
cout<<*++pt<<endl;
cout << ++*pt << endl;
cout << (*pt)++ << endl;
cout<<*pt++<<endl;
cout << pt << endl;
cout << *pt << endl;
}
pt为指向数组arr[0]地址的指针
++pt:使指针指向arr[1]的地址
*++pt:先将++引用于pt(因为++位于*右边),然后将*引用于被递增后的指针
因为前缀递增、前缀递减和解除引用运算符的优先级相同,以从右向左的方式进行结合
++*pt:先取得pt指向的值,再给值加1
(*pt)++:先对pt解引用,再进行后置自增(打印出副本的值为48.9,arr[2]的值为49.9)
*pt++:后缀递增和后缀递减的优先级比前缀运算符的优先级高,所以++运算符作用于pt后再解引用,打印出为arr[2]此时的值(此时指针指向arr[3],最后打印pt与*pt验证)
三、c风格字符串的比较
如果要知道字符数组中的字符串是不是mate,word是数组名,该代码word=="mate"可能不会像我们预想中工作。数组名实质上是数组的地址,同样,用引号括起的字符串常量也是其地址。两个地址必然是不同的。应该使用c风格字符串库中的strcmp()函数来比较。
函数原型
#include <cstring>
int strcmp(const char *str1, const char *str2);
参数
str1
:要比较的第一个字符串。str2
:要比较的第二个字符串。
返回值
- 如果
str1
小于str2
,则返回一个负整数。 - 如果
str1
等于str2
,则返回0
。 - 如果
str1
大于str2
,则返回一个正整数。 - (使用ASCII时,所有的大写字母的编码都比小写字母的小)
使用范例:
#include <iostream>
#include<cstring>
int main()
{
using namespace std;
char word[5] = "?ate";
for (char ch = 'a'; strcmp(word, "mate")!=0; ch++)
{
cout << word << endl;
word[0] = ch;
}
cout << "After loop ends,word is " << word << endl;
return 0;
}
该程序显示了一个单词,修改其首字母,再次显示,循环往复,直到strcmp()确定该单词与字符串'mate'相同。