labwc/src/common/string-helpers.c

80 lines
1 KiB
C
Raw Normal View History

2021-09-24 21:45:48 +01:00
// SPDX-License-Identifier: GPL-2.0-only
2020-10-09 19:46:59 +01:00
#include <ctype.h>
#include <stdarg.h>
2020-10-09 19:46:59 +01:00
#include <stdio.h>
#include <string.h>
#include "common/mem.h"
2023-01-31 03:35:13 +01:00
#include "common/string-helpers.h"
2020-10-09 19:46:59 +01:00
void
trim_last_field(char *buf, char delim)
{
char *p = strrchr(buf, delim);
if (p) {
*p = '\0';
}
}
2020-10-09 19:46:59 +01:00
static void
rtrim(char **s)
{
size_t len = strlen(*s);
if (!len) {
return;
}
char *end = *s + len - 1;
while (end >= *s && isspace(*end)) {
end--;
}
*(end + 1) = '\0';
}
char *
string_strip(char *s)
{
rtrim(&s);
while (isspace(*s)) {
s++;
}
return s;
}
void
string_truncate_at_pattern(char *buf, const char *pattern)
{
char *p = strstr(buf, pattern);
if (!p) {
return;
}
*p = '\0';
}
char *
strdup_printf(const char *fmt, ...)
{
size_t size = 0;
char *p = NULL;
va_list ap;
va_start(ap, fmt);
int n = vsnprintf(p, size, fmt, ap);
va_end(ap);
if (n < 0) {
return NULL;
}
size = (size_t)n + 1;
p = xzalloc(size);
va_start(ap, fmt);
n = vsnprintf(p, size, fmt, ap);
va_end(ap);
if (n < 0) {
free(p);
return NULL;
}
return p;
}