- 1.编一程序,将字符串“Hello,C++!”赋给一个字符数组,
然后从第一个字母开始间隔地输出该串(请用指针完成)。 - 代码如下
#include<iostream>
#include<string>
using namespace std;
int main() {
const char str[] = "Hello,C++!";
const char *p = str;
while ((*p) != '\0')
cout << *p++ << " ";
cout << endl;
return 0;
}
-
测试截图
-
2.编写一个函数,用于去掉字符串尾部的空格符。
函数原型为:char *mytrim(char *string);
其中参数string为字符串,返回值为指向string的指针。 - 代码如下:
#include<iostream>
#include<string>
#include<cstdio>
using namespace std;
char *mytrim(char *string) {
char *p = string;
int c1 = 0, c2 = 0;
while ((*p++) != '\0')
c1++;
cout << "The original length of the string is:" << c1 << endl;
for (int i = c1 - 1; string[i] == ' '; i--) //Reverse Search for spaces
c2++;
*(string + (c1- c2)) = '\0';
cout << "The string is now long:" << c2 << endl;
return string;
}
int main() {
char str[] = "Hello,C++! ";
cout << "The original string is:";
printf("%s\n",str);
cout << mytrim(str) << endl;
return 0;
}
- 测试截图
- 3.编写一个函数,用于去掉字符串前面的空格。
函数原型为:char *myltrim(char *string);
其中参数string为字符串,返回值为指向string的指针。 - 代码如下
#include<iostream>
#include<string>
#include<cstdio>
using namespace std;
char *mytrim(char *string) {
char *p = string;
int c1 = 0, c2 = 0;
while ((*p++) != '\0')
c1++;
cout << "The original length of the string is:" << c1 << endl;
for (int i = 0; string[i] == ' '; i++) //Find spaces from Start
c2++;
for (int i = 0; i < c2; i++)
string[i] = string[i + c2];
*(string + (c1 - c2)) = '\0';
cout << "The string is now long:" << c2 << endl;
return string;
}
int main() {
char str[] = " Hello,C++!";
cout << "The original string is:";
printf("%s\n", str);
cout << mytrim(str) << endl;
return 0;
}
- 测试截图