写一段可以讲输入字符串倒转过来的代码
时间: 2023-03-26 11:01:26 浏览: 71
可以使用以下代码实现字符串倒转:
```c
#include <stdio.h>
#include <string.h>
void reverse(char *str) {
int len = strlen(str);
for (int i = ; i < len / 2; i++) {
char temp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = temp;
}
}
int main() {
char str[100];
printf("请输入一个字符串:");
scanf("%s", str);
reverse(str);
printf("倒转后的字符串为:%s\n", str);
return ;
}
```
这段代码使用了一个 `reverse` 函数,该函数接受一个字符串指针作为参数,将字符串倒转。在 `main` 函数中,我们先读入一个字符串,然后调用 `reverse` 函数将其倒转,最后输出倒转后的字符串。
相关问题
写一段代码使输入字符串后可以判断输入的字符种类
好的,以下是代码:
#include <iostream>
#include <ctype.h>
using namespace std;
int main() {
string input;
cout << "请输入一个字符串:";
getline(cin, input);
for (int i = 0; i < input.length(); i++) {
if (isalpha(input[i])) {
cout << "字母 ";
} else if (isdigit(input[i])) {
cout << "数字 ";
} else if (isspace(input[i])) {
cout << "空格 ";
} else {
cout << "其它字符 ";
}
}
return 0;
}
如果您还有其它问题,请继续提问。
写一个自动机识别输入字符串的代码
好的,我来给你写一个简单的自动机识别输入字符串的代码。假设我们要识别的字符串只包含小写字母 a 和 b。
```
#include <iostream>
using namespace std;
bool isValid(string str) {
int state = 0; // 初始状态为 0
for (char c : str) {
if (c == 'a') {
if (state == 0) state = 1;
else if (state == 1) state = 0;
else return false; // 非法输入
} else if (c == 'b') {
if (state == 1) state = 2;
else if (state == 2) state = 1;
else return false; // 非法输入
} else {
return false; // 非法输入
}
}
return state == 1; // 只有在状态为 1 的情况下才是合法字符串
}
int main() {
string str;
cout << "请输入字符串:";
cin >> str;
if (isValid(str)) {
cout << "合法字符串" << endl;
} else {
cout << "非法字符串" << endl;
}
return 0;
}
```
这段代码中,我们使用了一个整数变量 `state` 来记录当前自动机的状态。初始状态为 0,如果读入了一个字符 a,就从状态 0 转移到状态 1;如果读入了一个字符 b,就从状态 1 转移到状态 2,或者从状态 2 转移到状态 1。如果读入的字符不是 a 或 b,或者在当前状态下无法接受该字符,则认为输入字符串非法。
最后,只有在状态为 1 的情况下才认为输入字符串合法。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)