Помогите решить задачу! Нужно добавить в с-строку перед пробелом запятую! Дополнительную строку нельзя использовать

char* PrintComma(char* Text) {
  for (int i = 0; i < strlen(Text); i++) {
    if (Text[i] == ' ') {
        Text[i] = ',';
    }
  }
  return Text;
}

Ответы (1 шт):

Автор решения: Maggot

Так как у вас метка С++ поехали.

1) в С++ надо использовать контейнеры. Или поменяйте метку на С и мы дадим Вам такойже ответ с realloc или используйте С++ по полной

Алгоритм.

т.к. Вам нельзя использовать новую строку будет увеличивать текущую.

1) Идете по строку пока не найдете пробел перед которым нет ','

2) Добавляете пробел в конец строки и сдвигаете все строку с конца до места вставки запятой на 1 символ

3) заменяете пробел на запятую после

4) профит

Ну а если у Вас С строка дергаете realloc на сайз+1 за место добавления пробела (line += " ";) и проделывайте все тоже самое

Фот код С.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>


char* AllocAndCopyStr(char* text)
{

    char* line = (char*)malloc(strlen(text) * sizeof(char) + 1);
    if(!line)
    {
        return NULL;
    }
    memcpy(line, text, strlen(text));
    line[strlen(text)] = '\0';

    return line;
}


void AddSpaceToStr(char** text)
{
    size_t old_size = strlen(*text);

    char* line = (char*)malloc(old_size * sizeof(char) + 2);
    assert(line != NULL);

    memcpy(line, *text, old_size);
    free(*text);

    line[old_size + 2] = ' ';
    line[old_size + 1] = '\0';

    *text = line;
}

void swap(char* a, char* b)
{
    char c = *a;
    *a = *b;
    *b = c;
}


int main()
{

    char* line = AllocAndCopyStr("a b c, d");
    if (!line)
    {
        return -1;
    }

    printf("%s\n", line);

    for (size_t i = 0; i < strlen(line); ++i)
    {
        if (i && line[i] == ' ' && line[i - 1] != ',')
        {
            AddSpaceToStr(&line);
            for (size_t j = strlen(line) - 1; j > i ; --j)
            {
                swap(&line[j], &line[j - 1]);
            }
            line[i] = ',';            
        }
    }


    printf("%s\n", line);
    free(line);

    return 0;
}

Вот код c++.

#include <iostream>
#include <string>
#include <algorithm>


int main() {

    std::string line{"a b c, d"};

    std::cout << line << std::endl;

    for (std::size_t i{0}; i < line.length(); ++i) {
        if (i && line[i] == ' ' && line[i - 1] != ',') {
            line += " ";
            for (std::size_t j = line.length() - 1; j > i ; --j) {
                std::swap(line[j], line[j - 1]);
            }
            line[i] = ',';            
        }
    }

    std::cout << line << std::endl;

    return 0;
}

UDP Ответ товарища - Georgy Firsov использование regex

#include <iostream>
#include <string>
#include <regex>

int main() 
{
    std::string str = "my string with, spaces";

    str = std::regex_replace(
        str,
        std::regex("( |, )"),
        ", "
    );

    std::cout << str;
}
→ Ссылка