所以我想做的是从最后一次出现的字符串中剪切一个字符串。例如
input = "Hellomrchicken"
input char = "c"
output = "cken"
问题是我无法使计数工作,因此我无法测试逻辑。我希望使用一个指针来执行此操作,理论上我将测试指针内的内容是否为==为空值。我在这里使用了一个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;
}
很抱歉不知道为什么代码被中途切断了
答案 0 :(得分:4)
如果您想从头开始定义此功能,原始帖子并不十分清楚,但它存在于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;
}
答案 1 :(得分:1)
在C中使用字符串时,我们通常使用所谓的C字符串或'\0'
终止字符串。这些只是char
的连续序列,以char '\0'
结尾,为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
从返回指针给出的位置进行复制。
答案 2 :(得分:0)
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;