二、 字符串

二、字符串

2.1字符串的定义

1.数组类型字符串:char str[] = "hello world";
2.指针类型字符串:const chat* str = "hello world";
3.string定义字符串:string str = "hello word";

C++中,字符串是经常会用到的一种数据类型,其有一些特殊的规定:

  1. 每个字符串都以’\0’结尾,由于这个特点字符串有一个额外的开销
  2. 定义指针类型时,指针必须是常指针,这是因为当你使用一个字符串字面值(例如:“hello world”)来初始化一个指向字符的指针时,该字符串字面值被视为常量,因此它的类型是 const char[]。因此,如果你定义一个指向字符的指针,它应该是 const char*,以匹配字符串字面值的不可修改性。
  3. 一般使用string来定义字符串,因为string支持修改字符串的内容,以及动态分配内存

2.2 练习题目1:

#include<iostream>
#include<string>
#include <vector>
using namespace std;

int main()
{
	const char* str1 = "12345";
	const char* str2 = "12345";
	char str3[] = "12345";
	char str4[] = "12345";
	if (str1 == str2) cout << "str1 == str2"   << endl;
	else cout << "str1 != str2" << endl;
	if (str3 == str4) cout << "str3 == str4" << endl;
	else cout << "str3 != str4" << endl;
	cout << "sizeof(str1):" << sizeof(str1) << endl;
	cout << "sizeof(str3):" << sizeof(str3) << endl;
	return 0;
}

这段代码的输出为:

str1 == str2
str3 != str4
sizeof(str1):4
sizeof(str3):6

因为当使用指针定义数组时,c++为了节省存储空间,会将str1和str2指向同一个地址,因为指针类型字符串是常量值。而数组类型字符串,即使存储空间相同,也会开辟两个空间来存储定义的字符串内存,故str3不等于str2。

练习题目2:替换空格

问题:请实现一个函数,把字符串中的每个空格替换成"%20"。例如,输入“We are happy.",则输出“We%20are%20happy.

#include<iostream>
#include<string>
#include <vector>
using namespace std;

void swap_space()
{
	char str[100] = "hello word word";
	cout << str << endl;
	int len = sizeof(str);
	if (str == nullptr || len <= 0) 
		return;
	int no_0_change_len = 0;
	int change_len = 0;
	int i = 0;

	while(str[i] !='\0')//计算str长度,一个空格算3个
	{
		if (str[i] == ' ' )
		{
			change_len++;
			cout << "change_len" << change_len << endl;
		}
		else 
		{ 

			no_0_change_len++;
		}
		i++;

	}
	int sum_len = no_0_change_len + 2 * change_len;
	cout << "sum_len:" << sum_len << endl;
	for  ( ; no_0_change_len>0; --no_0_change_len)
	{
		if (str[no_0_change_len] == ' ')
		{
			str[sum_len--] = '0';
			str[sum_len--] = '2';
			str[sum_len--] = '%';

		}
		else
		{
			str[sum_len--] = str[no_0_change_len];
		}
	}
	cout << str << endl;
	return;
}
int main()
{
	int a;
//	char str[] = "hello word";
	a = 1;
	swap_space();
	a = 5;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值