fix(string): fix algo to insert chars at location

This commit is contained in:
Jeremy Attali 2020-01-04 17:09:18 -05:00
parent 3d7eee792e
commit bc3264e9f1
3 changed files with 16 additions and 11 deletions

View File

@ -4,4 +4,4 @@
#include <glib.h>
void string_remove_at(char *str, int pos);
gchar *string_insert_char_at(gchar *str, gchar c, int pos);
gchar *string_insert_chars_at(gchar *str, gchar *chars, int pos);

View File

@ -189,7 +189,7 @@ void paint_update_temporary_text(struct swappy_state *state,
g_debug("received unicode: %d - utf8: %s (%d)", unicode, buffer, ll);
g_debug("text before: %s - cursor: %d", text->text, text->cursor);
char *new_text =
string_insert_char_at(text->text, buffer[0], text->cursor);
string_insert_chars_at(text->text, buffer, text->cursor);
g_free(text->text);
text->text = new_text;
text->cursor++;

View File

@ -8,22 +8,27 @@ void string_remove_at(gchar *str, int pos) {
memmove(&str[pos], &str[pos + 1], strlen(str) - pos);
}
gchar *string_insert_char_at(gchar *str, gchar c, int pos) {
gchar *string_insert_chars_at(gchar *str, gchar *chars, int pos) {
gchar *new_str;
int n = strlen(str);
if (str) {
new_str = g_new(gchar, n + 1 + 1); // one for the new char, one for the \0
if (str && chars) {
int n = strlen(str);
int m = strlen(chars);
int i = 0, j = 0;
for (int i = 0, j = 0; j < n + 1 || i < n; i++, j++) {
new_str = g_new(gchar, n + m + 1);
while (j < n + m) {
if (j == pos) {
new_str[j] = c;
j++;
for (int k = 0; k < m; k++) {
new_str[j++] = chars[k];
}
} else {
new_str[j++] = str[i++];
}
new_str[j] = str[i];
}
new_str[n + 1] = str[n];
new_str[j] = '\0';
} else {
new_str = NULL;
}