C语言源代码每两个字符串之后输出一个空格
时间: 2023-08-02 08:22:04 浏览: 39
可以采用如下的C语言代码实现:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str[1000], new_str[1000];
int i, j, len;
printf("请输入一个字符串:");
fgets(str, sizeof(str), stdin);
len = strlen(str);
j = 0;
for(i=0; i<len; i++)
{
if(i%2 == 1 && str[i] != '\n')
{
new_str[j] = ' ';
j++;
}
new_str[j] = str[i];
j++;
}
printf("\n输出新字符串:");
printf("%s", new_str);
return 0;
}
```
这个程序首先要求用户输入一个字符串,然后从输入的字符串中每两个字符之间插入一个空格,最后输出新字符串。具体实现过程是:定义两个字符数组`str`和`new_str`,分别用于存放输入的字符串和输出的新字符串;然后计算输入字符串的长度;接着遍历输入字符串中的每一个字符,如果该字符不是换行符且其下标为奇数,则在新字符串中插入一个空格;否则直接将该字符复制到新字符串中;最后输出新字符串。
相关问题
C语言源代码每四个字符串之后输出一个空格
好的,我可以帮你写一个简单的C语言程序来实现这个要求。你可以参考以下代码:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str[100];
printf("请输入字符串:");
scanf("%s", str);
int len = strlen(str);
for (int i = 0; i < len; i += 4) {
printf("%c%c%c%c ", str[i], str[i+1], str[i+2], str[i+3]);
}
return 0;
}
```
这个程序会要求你输入一个字符串,然后每四个字符输出一个空格,直到输出完整个字符串。希望对你有所帮助!
C语言代码通过对源程序字符串的扫描,分解出一个个的单词,根据单词符号及种别编码进行归类
。以下是一个简单的例子:
```c
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAX_LEN 100
int main() {
char input[MAX_LEN];
int len, i, j, k;
char token[MAX_LEN];
int symbol;
printf("请输入源程序:\n");
fgets(input, MAX_LEN, stdin);
len = strlen(input);
for (i = 0; i < len; i++) {
/* 跳过空格、换行、制表符等 */
if (isspace(input[i])) {
continue;
}
/* 扫描单词 */
j = i;
k = 0;
while (isalnum(input[j]) || input[j] == '_') {
token[k++] = input[j++];
}
token[k] = '\0';
i = j - 1;
/* 根据单词符号及种别编码进行归类 */
if (strcmp(token, "if") == 0) {
symbol = 1;
} else if (strcmp(token, "else") == 0) {
symbol = 2;
} else if (strcmp(token, "while") == 0) {
symbol = 3;
} else if (strcmp(token, "do") == 0) {
symbol = 4;
} else if (strcmp(token, "for") == 0) {
symbol = 5;
} else {
symbol = 0;
}
/* 输出单词及其符号及种别编码 */
printf("%s\t%d\n", token, symbol);
}
return 0;
}
```
在这个例子中,我们先读入源程序字符串,然后逐个扫描每个字符。对于空格、换行、制表符等空白字符,我们跳过不处理。对于字母、数字和下划线,我们把它们组成一个单词,并保存在临时数组 `token` 中。当遇到空白字符或非字母数字下划线时,我们认为一个单词扫描完毕,根据单词内容判断它的符号及种别编码,然后输出单词及其符号及种别编码。这个例子中,我们只识别了几个简单的关键字,实际编译器中需要识别更多种类的单词。