Quellcode durchsuchen

Add strcspn() and strndup()

tags/v0.9.3
Michael Brown vor 17 Jahren
Ursprung
Commit
7137c20ed1
2 geänderte Dateien mit 43 neuen und 4 gelöschten Zeilen
  1. 41
    4
      src/core/string.c
  2. 2
    0
      src/include/string.h

+ 41
- 4
src/core/string.c Datei anzeigen

@@ -279,6 +279,31 @@ size_t strspn(const char *s, const char *accept)
279 279
 }
280 280
 #endif
281 281
 
282
+#ifndef __HAVE_ARCH_STRCSPN
283
+/**
284
+ * strcspn - Calculate the length of the initial substring of @s which only
285
+ * 	contain letters not in @reject
286
+ * @s: The string to be searched
287
+ * @accept: The string to search for
288
+ */
289
+size_t strcspn(const char *s, const char *reject)
290
+{
291
+	const char *p;
292
+	const char *r;
293
+	size_t count = 0;
294
+
295
+	for (p = s; *p != '\0'; ++p) {
296
+		for (r = reject; *r != '\0'; ++r) {
297
+			if (*p == *r)
298
+				return count;
299
+		}
300
+		++count;
301
+	}
302
+
303
+	return count;
304
+}
305
+#endif
306
+
282 307
 #ifndef __HAVE_ARCH_STRPBRK
283 308
 /**
284 309
  * strpbrk - Find the first occurrence of a set of characters
@@ -541,9 +566,21 @@ void * memchr(const void *s, int c, size_t n)
541 566
 
542 567
 #endif
543 568
 
544
-char * strdup(const char *s) {
545
-	char *new = malloc(strlen(s)+1);
546
-	if (new)
547
-		strcpy(new,s);
569
+char * strndup(const char *s, size_t n)
570
+{
571
+	size_t len = strlen(s);
572
+	char *new;
573
+
574
+	if (len>n)
575
+		len = n;
576
+	new = malloc(len+1);
577
+	if (new) {
578
+		new[len] = '\0';
579
+		memcpy(new,s,len);
580
+	}
548 581
 	return new;
549 582
 }
583
+
584
+char * strdup(const char *s) {
585
+	return strndup(s, ~((size_t)0));
586
+}

+ 2
- 0
src/include/string.h Datei anzeigen

@@ -30,6 +30,7 @@ char * strrchr(const char * s, int c);
30 30
 size_t strlen(const char * s);
31 31
 size_t strnlen(const char * s, size_t count);
32 32
 size_t strspn(const char *s, const char *accept);
33
+size_t strcspn(const char *s, const char *reject);
33 34
 char * strpbrk(const char * cs,const char * ct);
34 35
 char * strtok(char * s,const char * ct);
35 36
 char * strsep(char **s, const char *ct);
@@ -41,6 +42,7 @@ void * memscan(void * addr, int c, size_t size);
41 42
 char * strstr(const char * s1,const char * s2);
42 43
 void * memchr(const void *s, int c, size_t n);
43 44
 char * strdup(const char *s);
45
+char * strndup(const char *s, size_t n);
44 46
 
45 47
 extern const char * strerror ( int errno );
46 48
 

Laden…
Abbrechen
Speichern