繁体   English   中英

如何从 C 中的字符串打印特定字符

[英]How to print a specific character from a string in C

我最近在练习循环。 我学会了如何打印:例如home to h 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 谢谢你。

这很容易做到。 例如

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类型的 object 能够存储传递的字符串的长度。

这是一个演示程序。

#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 );
    }
}

程序 output 是

home
hom
ho
h

你基本上会在你的循环中向后 go 。

代替:

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

你会有

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

您可以使用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;
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM