K
K
Konstantin2021-12-19 18:38:04
C++ / C#
Konstantin, 2021-12-19 18:38:04

How to remove an unnecessary character in a string and at the same time shorten the string itself?

There is a string, you need to delete a character in it so that the rest of the string remains and the size of the string (that is, an array of characters) decreases. I used calloc to allocate memory, but I can't figure out how to compress a string using the same realloc.

#include <stdlib.h>
#include <string.h>
#include <malloc.h>
#include <stdio.h> 
#define _CRT_SECURE_NO_WARNINGS  // от ошибки
#pragma warning(disable : 4996)

int main()
{
  char* ss;
  int n;

  system("chcp 1251");// переходим в консоли на русский язык
  system("cls");// очищаем окно консоли

  printf("Введите длину строки: ");
  scanf("%d", &n);

  ss = (char*)calloc(n, sizeof(char*));  // выделяем память под строку
  gets(ss);
  printf("Введите свое слово (не забываем про длину строки): ");
  scanf("%s", ss);

  for (int i = 0; i < n; i++)
  {
    if (ss[i] != NULL) // проверка на нулевой указатель
    {
      if (ss[i] == '*')  // тот самый символ, который мы ищем
      {
        for (int j = 0; ss[j] != '\0'; j++)
        {
          ss[j] = ss[j++];// здесь я заменял тот символ на следующий, тем самым перекидывая его в конец
        }
      }
    }
    else
    {
      printf("Error... Exit");
      exit(1);
    }
  }

  for (int i = 0; i < sizeof(ss); i++)// ну а тут пытался поменять размер
  {
    if (ss[i] == '\0')
    {
      ss = (char*)realloc(i, sizeof(char*));
      gets(ss);
    }
    else
      break;
  }

  free(ss);
  return 0;
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
C
CityCat4, 2021-12-19
@CityCat4

Wait a minute, I think I once solved such a problem ... Here.

/*-------------------------------------------------------------------------
            Unescape string againts some character

            Call: void strunescape(char *source, char symbol);
            Args: source - source string, is subject to change!
                  symbol - unescaping symbol

            Source string MUST be finished by \0'.
-------------------------------------------------------------------------*/
#include "make.h"

// Main function

void strunescape(char *source, char symbol)
{
  register int i = strlen(source);
  register int j;

  for(j = 0;j <= i;j++)
   if (source[j] == symbol)
     memmove(&source[j], &source[j + 1], i - j + 1);
}

What is the point - with a decrease of a line you simply pull it to a head in the same memory area. And so on until all occurrences of symbol are found.

D
Dmitry Belyaev, 2021-12-20
@bingo347

ss = (char*)calloc(n, sizeof(char*)); // выделяем память под строку
Here you allocate much more bytes than you need, sizeof(char*)it will be equal to 8 on 64-bit architectures, when sizeof(char)- 1. But you should not forget about the place under '\0'at the end of the line.
gets(ss);
printf("Введите свое слово (не забываем про длину строки): ");
scanf("%s", ss);
ss = (char*)realloc(i, sizeof(char*));
gets(ss);
Read what the function does gets. Again, the problem is with the size of the character. Well, it has a reallocslightly different signature. And in general realloc, a rather expensive operation, there is nothing to do it in a loop many times over one pointer, 1 time at the end is enough.
if (ss[i] != NULL) // проверка на нулевой указатель
Checking for NULL should be done immediately after memory allocation. But there is no need to do it in a cycle.
ss[j] = ss[j++];// здесь я заменял тот символ на следующий, тем самым перекидывая его в конец
The operation j++changesj
for (int i = 0; i < sizeof(ss); i++)// ну а тут пытался поменять размер
The operation sizeof(ss)will give size char*, that is, the size of the pointer, which corresponds to 8 on 64-bit architectures. To calculate the length of a string (terminated by the character '\0') there is a function strlen. And in this case, in general, you can count the number of deleted characters and calculate the length of the resulting string from it, which will be cheaper.
Well, according to the algorithm itself. Everything can be done in 1 pass, counting the characters to be removed and moving the current character back by the number of characters removed.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question