C语言学习过程记录22 练习2

1.保留整数

输入一个字符串str1,把其中的连续非数字的字符子串换成一个‘*’,存入字符数组str2 中,所有数字字符也必须依次存入 str2 中。输出str2。

样例输入:

@#%……%@1223524@#¥%#@¥??》》345()()——67

样例输出:

*1223524*345*67

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
	string str1;
	string str2;
	getline(cin,str1);
	int i = 0;
	for(i=0;i<str1.length();i++)
	{
		if(isdigit(str1[i])==0)
		{
			str1[i]='*';
		}
	}
	for(i=0;i<str1.length();i++)
	{
		int loc = 0;
		if(str1[i]=='*'&&str1[i+1]!='*')
		str2.push_back(str1[i]);
		else if(isdigit(str1[i])!=0)
		str2.push_back(str1[i]);
	}
	cout<<str2<<endl;
	return 0;
}

2.打印数字菱形

输入样例:6

输出样例:

     1
    121
   12321
  1234321
 123454321
12345654321
 123454321
  1234321
   12321
    121
     1

= 0;
	cin>>n;
	int i = 0;
	for(i=1;i<n;i++)
	{
		int j = 0;
		int c = 0;
		int count = 1;
		for(j=0;j<n-i;j++)
		{
			cout<<" ";
		}
		for(j=0;j<2*i-1;j++)
		{
			if(count<=i)
			{	c++;
				cout<<c;
				count++;
			}
			else
			{
				c--;
				cout<<c;
			}
			
		}
		cout<<endl;
	}
	int j = 0;
	int k = 1;
	for(i=0;i<2*n-1;i++)
	{
		if(k<=n)
		{
			j++;
			cout<<j;
			k++;
		}
		else
		{
			j--;
			cout<<j;
		}
	}
	cout<<endl;
	for(i=1;i<n;i++)
	{
		int j = 0;
		int c = 0;
		int count = 1;
		for(j=0;j<i;j++)
		{
			cout<<" ";
		}
		for(j=0;j<2*(n-i)-1;j++)
		{
			if(count<=n-i)
			{	c++;
				cout<<c;
				count++;
			}
			else
			{
				c--;
				cout<<c;
			}
			
		}
		cout<<endl;
	}
	return 0;
}

3.统计单词数目

从键盘输入一行字符,统计其中单词的个数,各单词以空格分隔,且空格数可以是多个。

输入样例:haha haha hahahaha     hahaha       hahahaha

输出样例:5

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
	string str;
	getline (cin,str);
	int count = 0;
	int i = 0;
	for(i=0;i<str.length();i++)
	{
		while(isalpha(str[i])!=0)
		{
			if(isalpha(str[i+1])==0)
			{
				count++;
				break;
			}
			i++;
		}
	}
	cout<<count<<endl;
	return 0;
}

3.移动m个数

有n个整数,使前面各数顺序向后移m个位置,最后m个数变成前面m个数,见图。写一函数:实现以上功能,在主函数中输入n个数和输出调整后的n个数。

输入样例:

10
1 2 3 4 5 6 7 8 9 10
2

输出样例:

9 10 1 2 3 4 5 6 7 8 
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
	int n = 0;
	int m = 0;
	vector <int> vec;
	cin>>n;
	int i = 0;
	for(i=0;i<n;i++)
	{
		int a = 0;
		cin>>a;
		vec.push_back(a);
	}
	cin>>m;
	for(i=0;i<m;i++)
	{
		vector<int>:: reverse_iterator it = vec.rbegin();
		int a = *it;
		vec.pop_back();
		vec.insert(vec.begin(),a);
	}
	for(i=0;i<vec.size();i++)
	{
		cout<<vec[i];
		if(i<vec.size()-1)
		cout<<" ";
	}
	return 0;
}

  • 7
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值