Add xy_str_start_with() and xy_str_delete_prefix()

This commit is contained in:
Aoran Zeng 2023-09-05 10:30:44 +08:00
parent 84ec2c20e9
commit 07ce4c217e
2 changed files with 45 additions and 1 deletions

View File

@ -2,7 +2,7 @@
* File : test_xy.c * File : test_xy.c
* Authors : Aoran Zeng <ccmywish@qq.com> * Authors : Aoran Zeng <ccmywish@qq.com>
* Created on : <2023-08-30> * Created on : <2023-08-30>
* Last modified : <2023-09-04> * Last modified : <2023-09-05>
* *
* test_xy: * test_xy:
* *
@ -31,11 +31,23 @@ main (int argc, char const *argv[])
putb(xy_str_end_with("abcdef", "abcdef")); // true putb(xy_str_end_with("abcdef", "abcdef")); // true
putb(xy_str_end_with("abcdef", "")); // true putb(xy_str_end_with("abcdef", "")); // true
putb(xy_str_start_with("abcdef", "abcdefg")); // false
putb(xy_str_start_with("abcdef", "abc")); // true
putb(xy_str_start_with("abcdef", "abcde")); // true
putb(xy_str_start_with("abcdef", "abcdef")); // true
putb(xy_str_start_with("abcdef", "")); // true
puts(xy_str_delete_suffix("abcdefg", "cdef")); // 不变 puts(xy_str_delete_suffix("abcdefg", "cdef")); // 不变
puts(xy_str_delete_suffix("abcdefg", "cdefgh"));// 不变 puts(xy_str_delete_suffix("abcdefg", "cdefgh"));// 不变
puts(xy_str_delete_suffix("abcdefg", "")); // 不变 puts(xy_str_delete_suffix("abcdefg", "")); // 不变
puts(xy_str_delete_suffix("abcdefg", "efg")); // abcd puts(xy_str_delete_suffix("abcdefg", "efg")); // abcd
puts(xy_str_delete_prefix("abcdefg", "cdef")); // 不变
puts(xy_str_delete_prefix("abcdefg", "0abcde"));// 不变
puts(xy_str_delete_prefix("abcdefg", "")); // 不变
puts(xy_str_delete_prefix("abcdefg", "abc")); // defg
xy_success("成功:输出成功内容"); xy_success("成功:输出成功内容");
xy_info("信息: 输出信息内容"); xy_info("信息: 输出信息内容");
xy_warn("警告:输出警告内容"); xy_warn("警告:输出警告内容");

32
xy.h
View File

@ -301,6 +301,38 @@ xy_str_end_with (const char* str, const char* suffix)
return true; return true;
} }
bool
xy_str_start_with (const char* str, const char* prefix)
{
size_t len1 = strlen(str);
size_t len2 = strlen(prefix);
if (0==len2) return true; // 空字符串直接返回
if (len1 < len2) return false;
const char* cur1 = str;
const char* cur2 = prefix;
for (int i=0; i<len2; i++)
{
if (*cur1 != *cur2) return false;
cur1++; cur2++;
}
return true;
}
char*
xy_str_delete_prefix (const char* str, const char* prefix)
{
char* new = xy_strdup(str);
bool yes = xy_str_start_with(str, prefix);
if (!yes) return new;
size_t len = strlen(prefix);
char* cur = new + len;
return cur;
}
char* char*
xy_str_delete_suffix (const char* str, const char* suffix) xy_str_delete_suffix (const char* str, const char* suffix)