char str[50];输入字符串:使用 gets() 或 scanf() 等函数输入字符串。printf("Enter a string: ");gets(str);

c语言数组怎么插星号

来源:这里教程网 时间:2026-02-21 16:49:45 作者:

如何在 C 语言数组中插入星号

为了在 C 语言数组中插入星号,需要使用以下步骤:

    定义一个字符数组:声明一个具有足够长度的字符数组来容纳字符串和星号。
<code class="c">char str[50];</code>
    输入字符串:使用
    gets()
    scanf()
    等函数输入字符串。
<code class="c">printf("Enter a string: ");
gets(str);</code>
    获取字符串长度:计算字符串的长度。
<code class="c">int len = strlen(str);</code>
    遍历字符串:使用一个循环遍历字符串的每个字符。
<code class="c">for (int i = 0; i < len; i++) {</code>
    在指定位置插入星号:在所需的字符位置插入星号。
<code class="c">str[i] = '*';</code>
    输出修改后的字符串:使用
    puts()
    函数输出修改后的字符串。
<code class="c">puts(str);</code>

示例代码:

<code class="c">#include <stdio.h>
#include <string.h>
int main() {
    char str[50];
    printf("Enter a string: ");
    gets(str);
    int len = strlen(str);
    for (int i = 0; i < len; i++) {
        if (i == 5) {
            str[i] = '*';
        }
    }
    puts(str);
    return 0;
}</code>

输出:

立即学习“C语言免费学习笔记(深入)”;

<code>Enter a string: Hello World
H*llo World</code>

相关推荐