8.23——字符指针

//用行指针变量求二维数组中每一行数组元素的和
#include<iostream>
using namespace std;
int main()
{
    int a[3][4] = { {1,2,3,4},{5,6,7,8},{9,10,11,12} };
    int(*p)[4] = a;
    int sum, i;
    while ( p - a < 3 )
    {
        sum = 0;
        for ( i = 0; i < 4; i++ )
            sum = sum + *((*p) + i);
        cout << "第" << p - a << "行的和为:" << sum << endl;
        p++;
    }
}

在c++中有三种方法引用字符串
(1)定义一个字符数组存放字符串,用数组引用字符串。
字符串存放在一个一维数组中,数组名代表数组的首地址。c++提供了很多字符串处理函数

//定义两个字符数组a[80]和b[80],将字符数组a的元素复制给字符数组b
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
    char a[80], b[80];
    cin.getline(a, 80);
    strcpy(b, a);
    cout << b << endl;
}

(2)定义一个字符串变量存放字符串,用字符串变量引用字符串

```cpp
//输入3个非空格的字符串,求最大的字符串,并将它输出
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
    string str1, str2, str3, maxstr;
    cin >> str1 >> str2 >> str3;
    if ( str1 >= str2 )
        maxstr = str1;
    else
        maxstr = str2;
    if ( maxstr < str3 )
        maxstr = str3;
    cout << "最大的字符串为:" << maxstr << endl;
}

(3)定义一个字符串指针,用指针变量引用字符串
c++在处理字符串时,将从字符串的首地址到字符串结束标志’\0’之间的内容作为一个整体看成一个字符串。字符指针代表该字符串的首地址,用户可以使用字符指针来引用字符串。
例如:
char*str=“C++program”等价于char str;str=“C++program”;
可以看出,str被定义为一个指针变量,指向字符型数据。对于一个数值型数组不能用数组名输出它的全部元素

//使用字符指针编程,将一个字符串的每个字符加1后生成一个新的字符串,并输出原来的字符串和处理后的字符串
#include<iostream>
#include<string>
using namespace std;
int main()
{
    char *p, a[80];
    p = "shagng hai";
    for ( int i = 0; p[i]!='\0'; i++ )
        a[i] = p[i] + 1;
    a[i] = '\0';
    cout << "原来的字符串" << endl;
    cout << p << endl;
    cout << "处理后的字符串" << endl;
    cout << a << endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值