假设有char str[100],户输入-串字符串,输出下标是偶数的元素以及下标是3的倍数的元素。 示例: 输入格式: I will miss you very,2019! //中间- 个英文空格 输出格式: Ilwil issyu vr,209 请选择程序语言▼ 输入格式: 12a 输出格式: After:298 输入格式: 78R 输出格式: error! 请用c语言实现
时间: 2024-02-18 11:00:28 浏览: 44
好的,以下是 C 语言代码实现:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
scanf("%[^\n]", str);
int len = strlen(str);
for (int i = 0; i < len; i++) {
if (i % 2 == 0 || i % 3 == 0) {
printf("%c", str[i]);
}
}
printf("\n");
return 0;
}
```
思路是遍历字符串的每一个元素,判断其下标是否为偶数或者是 3 的倍数,如果是则输出该元素。注意,由于输入的字符串中可能包含空格,因此使用 `%[^\n]` 来读取整行输入,直到遇到换行符为止。
相关问题
输入字符串str如“ABBCCCCAA”,则输出的结果是A1B2C4A2
好的,我明白了。这个问题可以使用一个计数器和一个指针来解决。以下是一个示例Python代码:
```python
def compress_str(input_str):
if not input_str:
return ""
compressed_str = ""
current_char = input_str[0]
char_count = 0
for char in input_str:
if char == current_char:
char_count += 1
else:
compressed_str += current_char + str(char_count)
current_char = char
char_count = 1
# Add the last character to the compressed string
compressed_str += current_char + str(char_count)
return compressed_str
```
你可以将需要压缩的字符串传递给`compress_str`函数,它将返回压缩后的字符串。例如,对于输入字符串`"ABBCCCCAA"`,函数将返回`"A1B2C4A2"`。
将一个字符数组str下标为3的倍数的元素赋给另外一个字符数组str2并输出str2C语言
好的,以下是代码实现:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "abcdefghijk";
char str2[5];
int i = 0, j = 0;
for(i = 0; i < strlen(str); i++) {
if(i % 3 == 0) {
str2[j] = str[i];
j++;
}
}
printf("%s", str2);
return 0;
}
```
输出结果为:`adgj`
解释一下代码:
首先定义了两个字符数组 `str` 和 `str2`,其中 `str` 为原始数组, `str2` 为目标数组,长度为3的倍数的字符将会被拷贝到 `str2` 中。
然后通过 `for` 循环遍历 `str` 数组,当下标为3的倍数时,将该字符拷贝到 `str2` 中,并将 `j` 的值加 1。
最后输出 `str2` 即可。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.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)