【问题标题】:Is there any way to return a string starting at a certain index without using the library functions有没有办法在不使用库函数的情况下返回从某个索引开始的字符串
【发布时间】:2021-04-26 07:30:35
【问题描述】:

char* string = "Hello, what's up?";

我只想回来

"at's up?"

【问题讨论】:

  • &string[9] 将“返回”。
  • 也没有库函数可以做到这一点...string+9 有效
  • 如果它在 for 循环中,我可以做 &str1[i] 吗?
  • 当然。为什么在循环中会有所不同?

标签: c substring c-strings function-definition


【解决方案1】:

如果您已经知道字符串的长度(因此知道前面的n 个字符不会超过结尾),您可以使用string + n&string[n],它们是“跳过”的等效方式" 字符串的第一个 n 字符。

#include <stdio.h>

int main(void) {
    char *str = "Hello!";
    
    printf("%s\n", str + 1); // ello!
    printf("%s\n", str + 3); // lo!

    char *str2 = str + 3;
    printf("%s\n", str2); // lo!
}

另一方面,如果您知道字符串的长度,则必须先使用循环确保不会超过结尾。您可以为此编写一个函数:

#include <stdio.h>

char *skip(char *s, size_t n) {
    while (*s && n--)
        s++;
    return s;
}

int main(void) {
    char *str = "Hello!";
    
    printf("%s\n", skip(str, 1));   // ello!
    printf("%s\n", skip(str, 3));   // lo!
    printf("%s\n", skip(str, 100)); // empty line

    char *str2 = skip(str, 3);
    printf("%s\n", str2); // lo!
}

【讨论】:

    【解决方案2】:

    你可以写一个函数。如果该函数不应使用标准的 C 字符串函数,那么它可以查看例如以下方式

    char * substr( char *s, size_t pos )
    {
        size_t i = 0;
    
        while ( i < pos && s[i] ) ++i;
    
        return s + i;
    }
    

    由于C不支持函数重载,所以上面的函数也可以写成这样

    char * substr( const char *s, size_t pos )
    {
        size_t i = 0;
    
        while ( i < pos && s[i] ) ++i;
    
        return ( char * )( s + i );
    }
    

    这是一个演示程序。

    #include <stdio.h>
    
    char * substr( const char *s, size_t pos )
    {
        size_t i = 0;
    
        while ( i < pos && s[i] ) ++i;
    
        return ( char * )( s + i );
    }
    
    int main(void) 
    {
        char * s = "Hello, what's up?";
        
        puts( substr( s, 9 ) );
        
        return 0;
    }
    

    程序输出是

    at's up?
    

    【讨论】:

    • 所有不需要的空格是怎么回事?
    • @MarcoBonelli 你是什么意思?
    • 我的意思是( char * )( s + i ) 而不是(char *)(s + i),或者puts( substr( s, 9 ) ) 而不是puts(substr(s, 9)),等等。似乎很奇怪。
    • @MarcoBonelli 不,它看起来非常好和可读。
    猜你喜欢
    • 2017-01-27
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 2021-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-08
    相关资源
    最近更新 更多