C++ string之 substr(), append() 算法

题目描述

•连续输入字符串,请按长度为8拆分每个字符串后输出到新的字符串数组; 
•长度不是8整数倍的字符串请在后面补数字0,空字符串不处理。 

实现方法1:

#include<iostream>
#include<string>
using namespace std;
int main() {
	string str;
	int count = 0;
	int remain_num = 0;
	while (cin >> str) {
		count = str.size() / 8;
		remain_num = str.size() % 8;
		for (int i = 0; i < count; i++) {
			string full,temp;
			for (int j = 0; j < 8; j++) {
				temp = str[j];
				full += temp;
			}
			cout << full << endl;
			str.erase(str.begin(), str.begin() + 8);
		}
        if(remain_num){
            string remain(8-remain_num, '0');
            str += remain;
            cout << str << endl;
        }
	}
}

实现方法2:

使用str.size()方法可以轻松的实现在一段字符串中提取部分内容

使用str.append()方法可以轻松实现拓展字符串

#include<iostream>
#include<string>
using namespace std;
int main() {
	string str;
	while (cin >> str) {
		int remain_num = str.size() % 8;
		while (str.size() >= 8) {
			cout << str.substr(0, 8) << endl;
			str = str.substr(8);//注意此处代表提取,从str[8]开始到str结尾的内容
		}
		if (remain_num) {
			str.append(8 - remain_num, '0');
			cout << str << endl;
		}
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
引用中的代码是一个C++程序示例,用于演示如何使用`string`类的`substr`函数来提取子串。这个函数有两种常用的用法: 1. `substr(pos, len)`: 提取从位置`pos`开始的长度为`len`的子串。其中,`pos`表示起始位置,`len`表示子串的长度。如果不指定`len`,则默认提取从`pos`到字符串末尾的所有字符。 2. `substr(pos)`: 提取从位置`pos`开始到末尾的子串。 在引用中的示例代码中,我们使用了`substr`函数来提取字符串"Hello, World!"中指定位置的子串。具体来说,我们从位置7开始提取子串,即"World!",并将其存储在变量`sub1`中。我们还演示了另一种用法,从位置7开始提取长度为5的子串,即"World",并将其存储在变量`sub2`中。 综上所述,`string.substr`函数用于提取C++字符串中的子串,可以根据指定的起始位置和长度或者起始位置到末尾来提取子串。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [C++string类中substr()函数的使用方法](https://blog.csdn.net/weixin_42258743/article/details/107782394)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [c++stringsubstr函数](https://blog.csdn.net/m0_74153798/article/details/131847142)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值