繁体   English   中英

从最后出现的字符缩短C字符串?

[英]Shorten C string from last occurence of a char?

所以我想做的是从上次出现的字符中切出一个字符串。 例如

input =  "Hellomrchicken"
input char = "c"
output = "cken"

问题是我无法计数,因此我无法测试逻辑。 我希望使用一个指针来做到这一点,并且从理论上讲,我会测试指针内的Content是否==到空值。 我在这里使用了while循环。 任何帮助表示赞赏,谢谢!

#include <stdio.h>
#include <stdlib.h>

char *stringcutter(char *s, char ch);
int count( char *s);

void main(){
    char input[100];
    char c;
    printf("Enter a string \n");
    gets(input);
    printf("Enter a char \n");
    scanf("%c", &c);
    stringcutter( *input , c );
    getchar();
    getchar();
    getchar();
}


char *stringcutter(char *s, char ch){
    int count = 0;
    // Count the length of string

            // Count the length of string
while ( check != '\0'){
            count++;
            s++;
            printf("Processed");


    printf("TRANSITION SUCCESSFUL /n");
    printf( "Count = %d /n" , count);


    // Count backwards then print string from last occurence

/*  for (i=count ; i != 0 ; i--){
        if (str[i] == ch)
            *s = *str[i];
        printf ( "Resultant string = %s", *s )
            */
            return 0; 
    }

对不起,不知道为什么代码被截断了一半

如果您想从头开始定义此函数,原始文章并未明确指出,但它存在于string.h ,并且看起来像

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

int main ()
{
    char input[] = "Hellomrchicken";
    char c = 'c';
    char *p;
    p = strrchr(input, c);
    printf("Last occurence of %c found at %d \n", c, p-input+1);
    return 0;
}

在C语言中使用字符串时,通常使用称为C字符串或以'\\0'结尾的字符串。 这些只是char的连续序列,以0字节char '\\0'结尾。

因此,下面是遍历C特有的字符串的一种方法:

char *my_string = "Hello, world";

char *p = my_string;
while (p != '\0')
{
    /* Do some work */

    p++;
}

您可以使用这样的循环来获取指向特定字符最后一次出现的指针。

char *from_last_instance_of(char *input, char c)
{
    char *last_instance_of_c = input;
    while (input != '\0')
    {
        if (*input == c)
            last_instance_of_c = input;

        input++;
    }
    return last_instance_of_c;
}

如您所见,所有工作都就位。 如果要在进一步操作之前复制字符串,请使用strcpy从返回的指针指定的位置进行复制。

strrchr()函数为您完成此操作。

char *output = strrchr(string_to_search, char_to_find);
int output_index = (output == NULL ? ERROR : output - string_to_search);

如果您想手动操作(使用c99语法)

char *output = NULL;
for(char p = string_to_search; *p; p++)
    if(*p == char_to_find)
        output = p;

暂无
暂无

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

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