【问题标题】:How to print a specific character from a string in C如何从C中的字符串中打印特定字符
【发布时间】:2022-01-18 15:52:27
【问题描述】:

我最近在练习循环。我学会了如何打印:例如 homeh ho hom home。通过使用

#include <stdio.h>
#include <string.h>

int main (){
    char s[100];
    
    printf("Input string = ");
    scanf("%[^\n]", s);
    
    for (int i=1; i<=strlen(s); i++){
        for(int j = 0; j<i; j++)
        printf("%c", s[j]);
        printf("\n");
    }

    return 0;

我怎样才能扭转它,所以它可以 home hom ho h 反而?谢谢。

【问题讨论】:

  • 不要使用 scanf:sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html。在这种情况下,你应该只做char *s = argv[1]。如果你要使用scanf,有很多问题需要注意,但至少要保护自己:if( scanf("%99[^\n]", s) != 1 ){ exit(1);}
  • scanf("%[^\n]", s);gets() 差。也不要使用。

标签: c loops for-loop nested-loops c-strings


【解决方案1】:

这很容易做到。例如

for ( size_t i = strlen( s ); i != 0; i-- )
{
    for ( size_t j = 0; j < i; j++ )
    { 
        putchar( s[j] );
    }
    putchar( '\n' );
}

另一种方式如下

for ( size_t i = strlen( s ); i != 0; i-- )
{
    printf( ".*s\n", ( int )i, s );
}

前提是int 类型的对象能够存储传递的字符串的长度。

这是一个演示程序。

#include <stdio.h>
#include <string.h>

int main( void )
{
    const char *s = "home";

    for (size_t i = strlen( s ); i != 0; i--)
    {
        printf( "%.*s\n", ( int )i, s );
    }
}

程序输出是

home
hom
ho
h

【讨论】:

  • 非常感谢您的详细解释,它对我的​​学习方式有所帮助,因为我是新手,所以我没有这么想。如果你介意我问的话。如果我希望它是homeomemee,我该怎么办?谢谢。
  • @atuy 这很容易。 for ( size_t i = 0, n = strlen( s ); i
【解决方案2】:

您可以使用putc 循环字符串,但了解缩短字符串并使用%s 打印字符串的破坏性方法也可能会有所帮助。例如:

#include <stdio.h>
#include <string.h>

int
main(int argc, char **argv)
{
    char *s = argc > 1 ? argv[1] : strdup("home");
    for( char *e = s + strlen(s); e > s; e -= 1 ){
        *e = '\0';
        printf("%s\n", s);
    }
    return 0;
}

请注意,这种方法具有破坏性。完成后,字符串为空。作为练习,解决这个问题可能会有所帮助。

【讨论】:

    【解决方案3】:

    你基本上会在你的循环中倒退。

    代替:

        for (int i=1; i<=strlen(s); i++){
    

    你应该有

        for (int i=strlen(s); i>0; i--){
    

    【讨论】:

    • @atuy 尝试学习 :) 哪个循环控制这种行为?基本上你需要弄清楚在那个循环中从哪里开始你的索引计数以及通过它的方式。你有 ij++-- - 找出每个应该是哪一个
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-08
    • 2018-03-16
    • 1970-01-01
    相关资源
    最近更新 更多