Loop to keep adding spaces in string?

放肆的年华 提交于 2019-12-02 13:18:36

问题


I have the following code:

sHexPic = string_to_hex(sPic);
    sHexPic.insert(sHexPic.begin() + 2,' ');
    sHexPic.insert(2," ");

I would like to know how I can put this into a counted loop and add a space after every 2nd character. So far all this does is make this string "35498700" into "35 498700", which in the end I want the final result to be something like "35 49 87 00".

I assume you would have to get the length of the string and the amount of characters in it.

I am trying to achieve this in c++/cli.

Thanks.


回答1:


Here's how it would be done in C++, using a string :) (I'm using C libraries cuz I'm more familiar with C)

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

using namespace std;

int main()
(
   string X;
   int i;
   int y;

   X = 35498700;
   y= X.size();

   for(i=2;i<y;i+=2)
   {
      X.insert(i," ");
      y=x.size(); //To update size of x
      i++; //To skip the inserted space
   }

   printf("%s",X);

   return 0;
}

Have fun :)

That would "probably" work. If it didn't then please mention so :)



来源:https://stackoverflow.com/questions/9612079/loop-to-keep-adding-spaces-in-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!