指针
/*数组清零
//编写一个函数,用于将一个int类型的数组清零(即将指定前n项元素全部置为0)数组以 - 1结尾,且 - 1不包括在此数组中。要求数组使用地址传递
//输入第一行数是数组元素
//第二行的数是需清零的元素个数n
//输出清零后的数组元素,(注意最后一个元素后不要带空格)
样例输入
503 87 512 61 908 170 897 275 653 426 154 509 612 677 765 703 - 1
5
样例输出
0 0 0 0 0 170 897 275 653 426 154 509 612 677 765 703
#include<iostream>
using namespace std;
void reo(int *p, int n)
{
int i = 0;
while (i<n)
{
p[i] = 0; i++;
}
}
int main()
{
int a[100], *p = a;
int i = 0, j = 0;
int n;
cin >> a[i];
while (a[i] != -1)
{
i++;
j++;
cin >> a[i];
}
cin >> n;
reo(a, n);
for (int i = 0; i<j - 1; i++)
{
cout << a[i] << " ";
}
cout << a[j - 1] << "\0" << endl;
}
*/
/*去除字符串首尾多余的空格
//用户输入一个字符串,首尾有多余的空格,编写程序来去除这些多余的空格。要求必须使用指针来完成本题。
//输入一个首尾有多余空格字符串。为了便于标识出尾部的空格,在字符串尾部额外添加了个#号表示字符串结束。字符串内部保证不会出现#号。
//输出去除空格后的字符串,同样在在字符串尾部额外添加了个#号表示字符串结束。
样例输入
my score #
样例输出
my score#
#include <iostream>
using namespace std;
int main()
{
char s[100];
cin.getline(s, 100, '\n');
char *head = s;//思路是直接从字符串里截取
char *tail = s;//并未对原字符串做大量修改
while (*head == ' ') head++;//确定头部位置,即省略头部空格
while (*tail != '#') tail++;//找到末尾
tail--;
while (*tail == ' ') tail--;//找到不是空格的字符
*(++tail) = '#';//后面加#
*(++tail) = 0;//字符串结尾
cout << head << endl;
return 0;
}
*/
/*查找子串
//编写程序,在字符串中查找子字符串,找到则返回第一个字符所在的位置(从1开始),找不到则显示“没有该子串”。要求字符串用字符数组存放,不使用库函数。字符串长度不超过100.
//输入第一行为待查找的字符串
//第二行为要查找的子字符串。
//输出第一个字符所在的位置(从1开始),若找不到则显示“没有该子串”。
样例输入
This is a book!
is
样例输出
3
#include <iostream>
#include <cstdlib>
#include <cmath>
int SearchString(char s[], char d[]);
using namespace std;
int main()
{
char s[81]; //储存一串字符
char d[10]; //储存要查找的字符
int flag;
//输入一串字符
//// cout<<"Input a string:";
gets_s(s);
//输入想要查找的字符
////cout<<"Input another string:";
gets_s(d);
//调用函数,输出结果
flag = SearchString(s, d);
if (flag == -1)
cout<<"Not found!"<<endl;
else
//// cout<<"Searching results:";
cout<<flag<<endl;
system("pause");
}
//函数功能:在字符数组s中查找子串d,返回d在s中首次出现的位置,若找不到,则返回-1
int SearchString(char s[], char d[])
{
int location = -1;
int i, j;
//第一层循环遍历被查找字符串
for (i = 0; s[i] != '\0'; i++)
{
//第二层循环遍历要查找的字符,若有不同的字符则退出该循环
for (j = 0; d[j] != '\0'; j++)
{
if (s[i + j] != d[j])
break;
}
//判断第二层循环是否全部执行,若全部执行则表示字符相等,保存位置
if (d[j] == '\0')
{
location = i + 1;
break;
}
}
return location;
}
*/

浙公网安备 33010602011771号