分别使用c语言和c++实现给定字符串的逆序输出
时间: 2023-08-12 11:06:54 浏览: 61
C语言实现:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
printf("请输入一个字符串:\n");
scanf("%s", str);
int len = strlen(str);
printf("逆序输出为:");
for(int i = len - 1; i >= 0; i--) {
printf("%c", str[i]);
}
printf("\n");
return 0;
}
```
C++实现:
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
cout << "请输入一个字符串:" << endl;
cin >> str;
int len = str.length();
cout << "逆序输出为:";
for(int i = len - 1; i >= 0; i--) {
cout << str[i];
}
cout << endl;
return 0;
}
```
相关问题
c语言编程:使用指针实现字符串逆序输出
可以用指针来实现字符串逆序输出,代码如下:
```c
#include <stdio.h>
#include <string.h>
void reverse(char *str) {
int length = strlen(str);
char *begin = str;
char *end = str + length - 1;
while (begin < end) {
char temp = *begin;
*begin = *end;
*end = temp;
begin++;
end--;
}
}
int main() {
char str[] = "Hello, world!";
printf("Original string: %s\n", str);
reverse(str);
printf("Reversed string: %s\n", str);
return 0;
}
```
这个程序中,我们定义了一个 `reverse` 函数,它接受一个指向字符串的指针。这个函数首先计算字符串的长度,然后定义了两个指针,一个指向字符串的开头,一个指向字符串的结尾。接下来,我们使用一个循环来交换开头和结尾的字符,直到两个指针相遇为止。最后,我们在 `main` 函数中调用 `reverse` 函数,并将结果输出到控制台上。
c语言 实现字符串逆序输出
以下是两种C语言实现字符串逆序输出的方法:
方法1:
```c
#include <stdio.h>
#include <string.h>
void reverse(char *s){
int n = 0;
int m = strlen(s) - 1;
while(n < m){
char tmp = s[n];
s[n] = s[m];
s[m] = tmp;
n++;
m--;
}
}
int main(){
char s[] = "Hello world";
reverse(s);
printf("%s\n",s); // 输出:dlrow olleH
return 0;
}
```
方法2:
```c
#include <stdio.h>
#include <string.h>
void reverse(char *s){
int i;
for(i = 0; i < strlen(s) / 2; i++){
char tmp = s[i];
s[i] = s[strlen(s) - i - 1];
s[strlen(s) - i - 1] = tmp;
}
}
int main(){
char s[] = "Hello world";
reverse(s);
printf("%s\n",s); // 输出:dlrow olleH
return 0;
}
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)