1 /* str/findprev.c - Find the previous instance of a character
2  * Copyright (C) 2001,2005  Bruce Guenter <bruce@untroubled.org>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
17  */
18 #include "str.h"
19 
20 /** Find the previous instance of the given character on or before \c pos */
str_findprev(const str * s,char ch,unsigned pos)21 int str_findprev(const str* s, char ch, unsigned pos)
22 {
23   char* p;
24   if (s->len > 0) {
25     if (pos >= s->len)
26       pos = s->len - 1;
27     for (p = s->s + pos; p >= s->s; --p)
28       if (*p == ch)
29 	return p - s->s;
30   }
31   return -1;
32 }
33 
34 #ifdef SELFTEST_MAIN
35 MAIN
36 {
37   str s = { "01234567890123456", 16, 0 };
38   str e = { 0, 0, 0 };
39   obuf_puti(&outbuf, str_findprev(&s, '6', 10)); NL();
40   obuf_puti(&outbuf, str_findprev(&s, '6', 6)); NL();
41   obuf_puti(&outbuf, str_findprev(&s, '6', 5)); NL();
42   obuf_puti(&outbuf, str_findprev(&s, '4', -1)); NL();
43   obuf_puti(&outbuf, str_findprev(&s, '6', -1)); NL();
44   obuf_puti(&outbuf, str_findprev(&e, '6', -1)); NL();
45 }
46 #endif
47 #ifdef SELFTEST_EXP
48 6
49 6
50 -1
51 14
52 6
53 -1
54 #endif
55