Заключить слова в кавычки в строке Си
Необходимо все вхождения слова заключить в ". Я нахожу вхождения, но не понимаю, как можно вставить символ. Допустим, есть строка: abc Hello abc world abc, после обработки она должна иметь вид: "abc" Hello "abc" world "abc". Я с помощью strstr() нахожу вхождения, но не понимаю, как дальше обработать. Использовать чистый Си. Мой код:
#include <stdio.h>
#include <string.h>
#include <conio.h>
int main(void)
{
char* c1;
char s1[] = "abc Heabcllo woabcrld";
char* buff[] = " ";
for (c1 = strstr(s1, "abc"); c1; c1 = strstr(s1, "abc")) {
//Здесь добавление символа
}
printf("%s\n", buff);
}
Ответы (2 шт):
Автор решения: Harry
→ Ссылка
Ну вот, например... не очень красиво, но работает, а на ночь глядя более красивое изобретать не тянет :)
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int main()
{
char s[] = "abc Heabcllo woabcrld";
char a[] = "abc";
int count = 0;
for(char * c = strstr(s,a); c; c = strstr(c+strlen(a),a)) ++count;
char *buf = malloc(strlen(s) + count*2 + 1);
strcpy(buf,s);
for(char * c = strstr(buf,a); c; c = strstr(c+strlen(a),a))
{
memmove(c+strlen(a)+2,c+strlen(a),strlen(c+strlen(a))+1);
*c = '\"';
strcpy(c+1,a);
*(c+strlen(a)+1) = '\"';
}
printf("%s\n",buf);
free(buf);
}
Автор решения: Stanislav Volodarskiy
→ Ссылка
Считаем "старые" фрагменты, выделяем буфер, копируем строку по кусочкам, заменяя "старые" фрагменты на "новые":
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
char *replace_all(const char *text, const char *old, const char *new) {
const int n = strlen(old);
const int m = strlen(new);
int count = 0;
for (const char *c = strstr(text, old); c != NULL; c = strstr(c + n, old)) {
++count;
}
char *result = malloc(strlen(text) + count * (m - n) + 1);
if (result == NULL) {
return NULL;
}
const char *c = text;
char *d = result;
for (; ; ) {
const char *c1 = strstr(c, old);
if (c1 == NULL) {
strcpy(d, c);
break;
}
const int k = c1 - c;
memcpy(d, c, k);
c = c1;
d += k;
memcpy(d, new, m);
c += n;
d += m;
}
return result;
}
int main() {
{
char *result = replace_all("abc Heabcllo woabcrld", "abc", "\"abc\"");
printf("%s\n", result);
free(result);
}
{
char *result = replace_all("abc Heabcllo woabcrld", "abc", "");
printf("%s\n", result);
free(result);
}
}
$ gcc -std=c11 -pedantic -Wall -Wextra -Werror replace_all.c && ./a.out "abc" He"abc"llo wo"abc"rld Hello world