《C程序設計語言》第二版練習4-1參考程序

//編寫函數strindex(s,t),它將返回字符串t在s中最右邊出現的位置。如果s中不包含t,則返回-1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 1000
int getline(char s2[], int lim);
int strindex(char s[], char t[]);
int main(void)
{
	char t1[] = "ould";
	char s1[SIZE];
	int loc = 0;
	while (getline(s1, SIZE) > 0)
	{
		loc = strindex(s1, t1);
		if (loc >= 0)
		{
			for (int k = 0; s1[k] != '\0'; k++)
			{
				printf("%c", s1[k]);
			}
		}
		else
			printf("Does not exsit\n");
		printf("The most right is s[%d]\n", loc);
	}
}
int getline(char s2[], int lim)
{
	int i, c;
	for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; i++)
	{
		s2[i] = c;
	}
	if (c == '\n')
	{
		s2[i++] = c;
	}
	s2[i] = '\0';
	return i;
}
int strindex(char s[], char t[])
{
	int i, j, k;
	for (i = strlen(s)-1; i >= 0; i--)
	{
		for (j = i, k = strlen(t)-1; k >= 0 && s[j] == t[k]; j--, k--)
		{ 
			;
		}
		if (k < 0)
			return i;
	}
	return -1;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章