计算机程序设计c++ 4.7:字符串的操作

字符串操作

字符串的操作还有很多,像大小写转换、查找、替换、
插入、删除、反转、去掉末尾空格,去掉前导空格等。
不论哪种操作,都是逐个字符去比较、移动跟复制,而“
是否处理完”的标志就是是否到达末尾的’\0’字符
。字符串
末尾的’\0’是其结束标记,一定要牢记。

  • 在VS2008及以上版本中调用strcpy、strcat等函数时由于安全原因会提示警告,解决办法头部添加下面语句:
    #define _CRT_SECURE_NO_WARNINGS

C++提供了一些字符串处理的库函数,方便字符串操作。
常见的有:

int strlen(char *s); //求字符串s的长度
char *strcpy(char *destin,char *source);//将字符串source复制到destin中
int strcmp(char *string1, char *string2);//比较string1和string2
char *strcat(char *destin, char *source); //将source连接到destin末尾,字符串拼接
char *strlwr(char *string);//string转换为小写
char *strupr(char *string); //stringz转换为大写

例子

假设有两个句子
Heavy rains are pushing water levels beyond the
limit.
Sluice gates at Three Gorges Dam opened to
discharge water.
开始由两个符号表示,请将它们合并为一段文字,然后查找
其中的“Heavy”替换为“Strong”,最后显示处理过的
文本。

问题分析:
目的:练习使用string类表示字符串;
先定义两个string对象,为它们赋值,用“+”号将它们连接起来;
使用find函数查找“Heavy”的位置,使用erase函数删除该字符串,再使用insert函数插入“Strong”

代码

#include<iostream>
#include<string>

using namespace std;

int main()
{
 string text1("Heavy rains are pushing water levels beyond the limit.");
 string text2, text3;
 int k;
 text2 = "Sluice gates at Three Gorges Dam opened to
discharge water.";
 text3 = text1 + text2;
 k = text3.find("Heavy");
 text3.erase(k, sizeof("Heavy")-1);  //删除Heavy, 末尾多一个\0,需减1
 text3.insert(k, "Strong");  // 在k位置插入Strong
 cout << text3 << endl;
}
return 0;

运行结果

Strong rains are pushing water levels beyond the
limit. Sluice gates at Three Gorges Dam opened
to discharge water.

总结

①行末的注释是对本行的注释;
#include <iostream> //包含需要的头文件
②整行的注释是对下面的程序的注释;

//为对象text2赋值
text2="Sluice gates at Three Gorges Dam opened to discharge water.";

③文本是计算机信息处理的很重要的内容。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

uncle_ll

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值