如何重新排列字符串中的字符?

时间:2012-03-08 18:43:49

标签: c++-cli

以下代码可以正常使用:

sCharacterUid = "394F73";
size_t pos;
sPos1 = sCharacterUid.substr(4,1);
sPos2 = sCharacterUid.substr(5,1);
sPos3 = sCharacterUid.substr(2,1);
sPos4 = sCharacterUid.substr(3,1);
sPos5 = sCharacterUid.substr(0,1);
sPos6 = sCharacterUid.substr(1,1);
sCharacterUid = sPos1 + sPos2 + " " + sPos3 + sPos4 + " " + sPos5 + sPos6;
String^ sfCharacterUid = gcnew String(sCharacterUid.c_str());

但我想知道如何减少执行此任务所需的代码量。

这是在c ++ / cli。

感谢。

2 个答案:

答案 0 :(得分:2)

乍一看,为什么不呢

sPos1 = sCharacterUid.substr(4,2); 
sPos3 = sCharacterUid.substr(2,2);
sPos5 = sCharacterUid.substr(0,2);
sCharacterUid = sPos1 + " " + sPos3 + " " + sPos5; 

或者

string result="";
for (i=4;i>=0;i-=2)
  result += sCharacterUid.substr(i,2) + " ";

或者,使用原始字符可能更有效。

char result=[9];
char* dest=result;
char* source = sCharacterUid.c_str();
for (i=4;i>=0;i-=2)
{
   *dest++ = source[i];
   *dest++ = source[i+1];
   *dest++ = ' ';
}
*(--dest)='\0';
String^ sfCharacterUid = gcnew String(result);

答案 1 :(得分:1)

std::string & S = sCharacterUid;
S = S.substr (4, 2) + " " + S.substr (2, 2) + " " + S.substr (0, 2);