#include <iostream> #include <cstdio> using namespace std; void change(char *str, int &count); bool symbol(char *str, char ch); int main() { setlocale(LC_ALL, "RUSSIAN"); char str[100] = "#rkt:# afet:rk: faktrlaa:etqg"; //набор символов. int count = 0; //счётчик элементов. cout << str << endl; change(str, count); cout << str << ' ' << '\n' << "Количество замен: " << count << endl; return 0; } void change(char *str, int &count) { do { while (*str++) { if (*str == ':') { char temp = *str; *str = *(str + 1); *(str + 1) = temp; } } } while (*str); } 

Question 1st. How to make the do while loop work several times. In my case, there is a shift by 1 element. As I understand it, instead of while (* str) you need to write something else, as I understand it while (* str) is a condition. Question 2nd. How to count the number of characters ':' in the same function. Variable count declared as a link, is this correct?

  • Maybe there is some function that checks the string for the content of the character? - Ilya
  • Why not just use string and create a new string? - AivanF.
  • I want to change the line itself - Ilya

1 answer 1

Simple passage through the array. If it occurs : - do not save this symbol, but increment the counter. If the other - then save, but taking into account the offset. Each iteration of the current character is stored in str[0] , and the previous, it turns out, in negative indices.

 #include <iostream> #include <cstdio> using namespace std; void change(char *str, int &count); int main() { char str[100] = "#rkt:# afet:rk: faktrlaa:etqg"; //набор символов. int count = 0; //счётчик элементов. cout << str << endl; change(str, count); cout << str << ' ' << '\n' << "Количество замен: " << count << endl; return 0; } void change(char *str, int &count) { count = 0; while (*str) { if (str[0] == ':') { count++; } else { str[-count] = str[0]; } str++; } } 
  • Thanks, it works, I will disassemble now how to do it in while - Ilya
  • @Ilya is possible without for, and without a constant, yes. Updated code, take a look. - AivanF.
  • thank you very much, this is more familiar to me - Ilya