用C语言编写一个程序,输入一个字符串,反转字符串并输出
时间: 2024-03-27 08:37:22 浏览: 28
以下是用C语言编写的程序,输入一个字符串,反转字符串并输出:
```
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
int len, i, j;
char temp;
printf("请输入一个字符串:");
scanf("%s", str);
len = strlen(str);
for (i = 0, j = len - 1; i < j; i++, j--) {
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
printf("反转后的字符串:%s", str);
return 0;
}
```
程序首先使用scanf()函数读取用户输入的字符串,并使用strlen()函数获取该字符串的长度。然后,程序使用一个for循环,从字符串的两端开始,依次交换字符,以达到反转字符串的目的。最后,程序输出反转后的字符串。
相关问题
以递归方式编写一个C语言程序,倒序输出字符串s
好的,下面是一个递归方式输出字符串s的C语言程序。
```c
void reverse(char* s) {
if (*s) {
reverse(s + 1);
printf("%c", *s);
}
}
```
在上面的代码中,我们定义了一个名为`reverse`的函数,该函数以字符串`s`作为参数。该函数的主要思想是通过递归方式输出字符串`s`。如果`s`不是空字符串,我们将递归调用`reverse`函数并移动到下一个字符,直到我们到达字符串的末尾。然后,我们输出当前字符。
在调用此函数时,只需传递要反转的字符串即可:
```c
char str[] = "Hello, World!";
reverse(str);
```
输出为:`!dlroW ,olleH`
希望能帮到你!
用C语言编写一个函数,实现逆向输出字符串的单词
以下是用C语言编写一个函数,实现逆向输出字符串的单词的例子:
```c
#include<stdio.h>
#include<string.h>
void reverseWords(char *s) {
int len = strlen(s);
int i = 0, j = 0;
while (i < len) {
while (i < len && s[i] == ' ') i++;
if (i >= len) break;
j = i + 1;
while (j < len && s[j] != ' ') j++;
reverse(s + i, s + j);
i = j;
}
reverse(s, s + len);
}
void reverse(char *begin, char *end) {
char temp;
while (begin < end) {
temp = *begin;
*begin++ = *end;
*end-- = temp;
}
}
int main() {
char str[] = "I love programming";
printf("Original string: %s\n", str);
reverseWords(str);
printf("Reversed words: %s\n", str);
return 0;
}
```
输出:
```
Original string: I love programming
Reversed words: programming love I
```
该函数首先使用两个指针 `i` 和 `j` 遍历字符串,以找出每个单词的起始位置和结束位置,然后使用 `reverse` 函数将每个单词反转,最后使用 `reverse` 函数将整个字符串反转。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)