mirror of
https://git.libssh.org/projects/libssh.git
synced 2025-11-30 13:01:23 +03:00
misc: Add ssh_strreplace()
Pair-Programmed-With: Sahana Prasad <sahana@redhat.com> Signed-Off-by: Sahana Prasad <sahana@redhat.com> Signed-Off-By: Andreas Schneider <asn@cryptomilk.org> Reviewed-by: Jakub Jelen <jjelen@redhat.com>
This commit is contained in:
@@ -98,4 +98,5 @@ int ssh_quote_file_name(const char *file_name, char *buf, size_t buf_len);
|
|||||||
int ssh_newline_vis(const char *string, char *buf, size_t buf_len);
|
int ssh_newline_vis(const char *string, char *buf, size_t buf_len);
|
||||||
int ssh_tmpname(char *template);
|
int ssh_tmpname(char *template);
|
||||||
|
|
||||||
|
char *ssh_strreplace(char *src, const char *pattern, const char *repl);
|
||||||
#endif /* MISC_H_ */
|
#endif /* MISC_H_ */
|
||||||
|
|||||||
50
src/misc.c
50
src/misc.c
@@ -1786,4 +1786,54 @@ err:
|
|||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @internal
|
||||||
|
*
|
||||||
|
* @brief Finds the first occurence of a patterm in a string and replaces it.
|
||||||
|
*
|
||||||
|
* @param[in] src Source string containing the patern to be replaced.
|
||||||
|
* @param[in] pattern Pattern to be replaced in the source string.
|
||||||
|
* Note: this function replaces the first occurence of pattern only.
|
||||||
|
* @param[in] replace String to be replaced is stored in replace.
|
||||||
|
*
|
||||||
|
* @returns src_replaced a pointer that points to the replaced string.
|
||||||
|
* NULL if allocation fails.
|
||||||
|
*/
|
||||||
|
char *ssh_strreplace(char *src, const char *pattern, const char *replace)
|
||||||
|
{
|
||||||
|
char *p = NULL;
|
||||||
|
char *src_replaced = NULL;
|
||||||
|
size_t len_replaced;
|
||||||
|
|
||||||
|
if (pattern == NULL || replace == NULL) {
|
||||||
|
return src;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ((p = strstr(src, pattern)) != NULL) {
|
||||||
|
size_t offset = p - src;
|
||||||
|
size_t len = strlen(src);
|
||||||
|
size_t pattern_len = strlen(pattern);
|
||||||
|
size_t replace_len = strlen(replace);
|
||||||
|
|
||||||
|
if (replace_len != pattern_len) {
|
||||||
|
len_replaced = strlen(src) + replace_len - pattern_len + 1;
|
||||||
|
} else {
|
||||||
|
len_replaced = strlen(src) + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
src_replaced = (char *)malloc(len_replaced);
|
||||||
|
|
||||||
|
if (src_replaced == NULL) {
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
memset(src_replaced, 0, len_replaced);
|
||||||
|
memcpy(src_replaced, src, offset);
|
||||||
|
memcpy(src_replaced + offset, replace, replace_len);
|
||||||
|
memcpy(src_replaced + offset + replace_len, src + offset + pattern_len, len - offset - pattern_len);
|
||||||
|
}
|
||||||
|
|
||||||
|
return src_replaced; /* free in the caller */
|
||||||
|
}
|
||||||
|
|
||||||
/** @} */
|
/** @} */
|
||||||
|
|||||||
Reference in New Issue
Block a user