#include <iostream> #include <cstdio> using namespace std; void change(char *str); int main() { setlocale(LC_ALL, "RUSSIAN"); char str[100] = "The sun is hot."; cout << str << endl; change(str); cout << str << endl; return 0; } void change(char *str){ char chs[] = ", "; while (*str) { if (*str == ' ') { memcpy(str, chs, strlen(chs)); str += strlen(chs); } else { str++; } } } 

Help deal with the task. I do not understand how to move subsequent elements by one position. I should get a string longer than the original. enter image description here

  • Will not work. Calling memcpy, you simply wipe the next byte after the detected space (by the way, you can see it yourself). Assuming that there is enough space in the array after the text, you need to copy (for example, by calling memove) the entire tail, i.e. move the text to the right with the space, write a comma and skip the space shifted to the right, repeat the search for the next space. - avp
  • Immediately from C ++ only cout. - Monah Tuk

2 answers 2

Like that:

 void change(char *str) { char chs[] = ", "; for(;*str;++str) { if (*str == ' ') { memmove(str+strlen(chs),str+1,strlen(str+1)+1); memmove(str,chs,strlen(chs)); ++str; } } } 

memmove always handles overlapping areas correctly. We displace a line, clearing a place for the pasted, and we interpose. Accordingly, we move the pointer, and then again read the space ...

Minus your approach - you need to ensure that there is enough space in the selected array for all inserts.

  • thanks, as I understand you in the memmove string (str + strlen (chs), str + 1, strlen (str + 1) +1) ;, roughly speaking, increase the length of the string, and what would not be a minus need to use a dynamic array? - Ilya
  • @Ilya Yes. You can just go through the line, calculate how many spaces there are, calculate the new length of the line, select it dynamically and go in a loop, copying characters from one line to the second, only inserting a comma before the space ... - Harry

The tag is C + +, so here is the solution using the possibilities thereof:

 #include <iostream> using namespace std; void change(string &str); int main() { //setlocale(LC_ALL, "RUSSIAN"); string str = "The sun is hot."; cout << str << endl; change(str); cout << str << endl; return 0; } void change(string &str) { for (string::size_type i = 0; i < str.size(); ++i) { if (str[i] == ' ') { str.insert(i, ","); i++; } } } 

Check: http://ideone.com/YLAYNa