Wstawianie znaków do ciągu


Chcę dodać
""
do
{"status": true}
, aby wiersz wyglądał następująco:
"{" status ":" true "}"  ... Jak mogę wstawić znaki do ciągu w określonych miejscach? 
Próbowałem
strncat ()
, ale nie mogłem uzyskać pożądanego rezultatu. Czytałem, że do tego trzeba stworzyć własną funkcję. Czy ktoś może mi pokazać przykład?
Zaproszony:
Anonimowy użytkownik

Anonimowy użytkownik

Potwierdzenie od:

Tak, w tym celu musisz napisać własną funkcję.
Zauważ, że ciąg w C to
char []
, który jest tablicą znaków i ma stały rozmiar.
To, co możesz zrobić, to utworzyć nową linię, która służy jako wynik, skopiować do niej pierwszą część tematu, dodać wiersz pośrodku i dodać drugą połowę tematu.
Kod wygląda mniej więcej tak,
// inserts into subject[] at position pos
void append(char subject[], const char insert[], int pos) {
char buf[100] = {};// 100 so that it's big enough. fill with zeros
// or you could use malloc() to allocate sufficient space
// e.g. char *buf = (char*)malloc(strlen(subject) + strlen(insert) + 2);
// to fill with zeros: memset(buf, 0, 100); strncpy(buf, subject, pos);// copy at most first pos characters
int len = strlen(buf);
strcpy(buf+len, insert);// copy all of insert[] at the end
len += strlen(insert);// increase the length by length of insert[]
strcpy(buf+len, subject+pos);// copy the rest strcpy(subject, buf);// copy it back to subject
// Note that subject[] must be big enough, or else segfault.
// deallocate buf[] here, if used malloc()
// e.g. free(buf);
}

Przykład roboczy tutaj
http://codepad.org/Z2bL5vPx
Anonimowy użytkownik

Anonimowy użytkownik

Potwierdzenie od:

Użyj
sprintf ()
.
const char *source = "{\"status\":\"true\"}";/* find length of the source string */
int source_len = strlen(source);/* find length of the new string */
int result_len = source_len + 2;/* 2 quotation marks *//* allocate memory for the new string (including null-terminator) */
char *result = malloc((result_len + 1) * sizeof(char));/* write and verify the string */
if (sprintf(result, "\"%s\"", source) != result_len) {/* handle error */ }/* result == "\"{\"status\":\"true\"}\"" */
Anonimowy użytkownik

Anonimowy użytkownik

Potwierdzenie od:

Próbowałem zaimplementować strinsert i wkleiłem go poniżej. Kompiluje i testuje z VS2010.
Funkcja pobiera wskaźnik do buforu docelowego, rozmiar buforu docelowego, ciąg do wstawienia oraz lokalizację do wstawienia ciągu. Funkcja zwraca -1 w przypadku błędu, w przeciwnym razie zwraca rozmiar bufora docelowego. Jeśli bufor docelowy jest zbyt mały, aby pomieścić wstawiony ciąg, zmienia rozmiar buforu za pomocą funkcji realloc i zwraca nowy rozmiar buforu.
Użyłem memmove zamiast strncpy, ponieważ uważam, że strncpy jest niezdefiniowane, gdy źródło i miejsce docelowe nakładają się. Jest to możliwe, jeśli wstawiony wiersz jest mniejszy niż ilość przenoszonej pamięci.
#include "stdafx.h"
#include <string.h>
#include <stdlib.h>
#include <malloc.h>
#include <assert.h>int strinsert(char **dest, size_t destsize, char *ins, size_t location)
{
size_t origsize = 0;
size_t resize = 0;
size_t inssize = 0; if (!dest || !ins)
return -1;// invalid parameter if (strlen(ins) == 0)
return -1;// invalid parameter origsize = strlen(*dest);
inssize = strlen(ins);
resize = strlen(*dest) + inssize + 1;// 1 for the null terminator if (location > origsize)
return -1;// invalid location, out of original string// resize string to accommodate inserted string if necessary
if (destsize < resize)
*dest = (char*)realloc(*dest, resize);// move string to make room for insertion
memmove(&(*dest)[location+inssize], &(*dest)[location], origsize - location);
(*dest)[origsize + inssize] = '\0';// null terminate string// insert string
memcpy(&(*dest)[location], ins, inssize); return max(destsize, resize);// return buffer size
}void check(int retVal)
{
if (retVal < 0)
{
assert(!"error code returned!\n");
exit(1);
}
}#define STARTSTRING "Hello world!"int _tmain(int argc, _TCHAR* argv[])
{
// initialize str
int bufsize = strlen(STARTSTRING) + 1 + 10;// added 1 for null terminator and 10 to test resize on demand
int prevbufsize = 0;
char *str = (char*)malloc(bufsize);
strncpy_s(str, bufsize, STARTSTRING, strlen(STARTSTRING));
printf("str = %s\n", str);// test inserting in the middle
prevbufsize = bufsize;
bufsize = strinsert(&str, bufsize, "awesome ", 6);
assert(bufsize == prevbufsize);// this should not resize the buffer as it has room for 10 more bytes
check(bufsize);
printf("str = %s\n", str);// test inserting at front
prevbufsize = bufsize;
bufsize = strinsert(&str, bufsize, "John says ", 0);
assert(bufsize > prevbufsize);
check(bufsize);
printf("str = %s\n", str);// test inserting char in the middle
prevbufsize = bufsize;
bufsize = strinsert(&str, bufsize, "\"", 10);
assert(bufsize > prevbufsize);
check(bufsize);
printf("str = %s\n", str);// test inserting char at end
prevbufsize = bufsize;
bufsize = strinsert(&str, bufsize, "\"", strlen(str));
assert(bufsize > prevbufsize);
check(bufsize);
printf("str = %s\n", str); free(str);
return 0;
}

Oto wyjście:

str = Hello world!
str = Hello awesome world!
str = John says Hello awesome world!
str = John says "Hello awesome world!
str = John says "Hello awesome world!"
Anonimowy użytkownik

Anonimowy użytkownik

Potwierdzenie od:

#include <stdio.h>
#include<stdlib.h>
#include<strings.h>
//{"status":true}\0_ _
//{"status": true " } \0/*
* parses the string, reallocates and shifts chars as needed, not generic though
*/int
insertQuotes(char ** original, int sizeOriginal)
{
int i = 0;
char * start = NULL;
char * temp = NULL;
long lenLeft = 0; int newSize = sizeOriginal + 2; if(*original == NULL)
return -1; *original = realloc(*original, newSize);
if (*original) {
start = strstr(*original, ":");
temp = *original + newSize - 1;
*temp = '\0';
temp--;
*temp = '}';
temp--;
*temp = '"';
temp--; while (temp > start + 1) {
*(temp) = *(temp - 1);
temp--;
}
*temp = '"';
return 0;
} else {
return -1;
}
}int main()
{
char * original = NULL;
int retval = 0; original = (char *)malloc(sizeof("{\"status\":true}"));
if (!original) return 1; strncpy(original, "{\"status\":true}", sizeof("{\"status\":true}")); retval = insertQuotes(&original, sizeof("{\"status\":true}"));
if (!retval) {
printf("\nnew original is [%s]", original);
}
free(original);
return 0;
}

Aby odpowiedzieć na pytania, Zaloguj się lub Zarejestruj się