簡體   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