Yêu cầu:
- Viết hàm tìm vị trí xuất hiện của kí tự c trong chuỗi kí tự. Việc tìm kiếm kí tự c bắt đầu từ vị trí chỉ định sIdx.
- Nếu tìm thấy trả về chỉ số mảng kí tự
- Nếu không tìm thấy trả về -1
Giải thuật:
- Duyệt mảng và so sánh với kí tự c
/******************Get position of character*************** * When Who What * 03/05/2016 vncoding create ***********************************************************/ #include <conio.h> #include <stdio.h> int getPosStr(const char* s, char c, int sIdx); void main() { char s[] = "vncoding blog for every one"; char c = 'o'; printf("\'%c\' at index = %d\n", c, getPosStr(s, c, 10)); printf("\'%c\' at index = %d", c, getPosStr(s, c, 20)); getch(); } /********************************************* Function : getPosStr() Parameter: [IN] s: string [IN] c: characeter [IN] sIdx: starting point to search Return : index where c occurs **********************************************/ int getPosStr(const char* s, char c, int sIdx) { int idx; for (idx = sIdx; s[idx] != NULL; idx++) { if (s[idx] == c) { return idx; } } return -1; }
Kết quả:
Leave a Reply
You must be logged in to post a comment.