我的输入字符串是\\?\bac#dos&ven_bb&prod_open-v&rev_5001#1&7f6ac24&0&353020304346333030363338#{53f56307-b6bf-11d0-94f2-00a0c91efb8b}
所需输出为bac\dos&ven_bb&prod_open-v&rev_5001\1&7f6ac24&0&353020304346333030363338_0
我已经写了下面的代码,但不工作…需要帮助是找出问题。
原谅我的无知:)也让我知道,如果有更好和有效的方法来做这件事。
输出字符串的规则是
在第二个字符串中,我将删除所有“\”和“?”。在哪里可以看到“#”我将其替换为“\”。第二个字符串只有在你看到字符“{”,但不包括“#”在它的末尾。
谢谢
int main()
{
char s[] = "\\?\bac#dos&ven_bb&prod_open-v&rev_5001#1&7f6ac24&0&353020304346333030363338#{53f56307-b6bf-11d0-94f2-00a0c91efb8b}";
char s1[] = {0};
printf("OUtput string is : ");
for(int i = 0; s[i] != '{'; i++)
{
if(s[i] != '\\' && s[i] != '?')
{
int j = 0;
if(s[i] == '#')
{
s1[j] = '\\';
continue;
}
s1[j] = s[i];
j++;
}
}
for(int i = 0; s1[i] != '\0'; i++)
{
cout<<s1[i];
}
getch();
}
最佳答案
注意j
的固定范围。在您的版本中,您总是分配给s1[0]
。
for(int i = 0, j = 0; s[i] != '{'; i++)
{
if(s[i] != '\\' && s[i] != '?')
{
// int j = 0;
if(s[i] == '#')
{
s1[j] = '\\';
}
else
{
s1[j] = s[i];
}
j++;
}
}
另一件事是为新字符串分配足够的空间。因为您没有指定size
char s1[] = {0};
声明大小为1的数组。你需要做如下事情:char s1[sizeof(s)] = { 0 }; // the size of the old array, since we don't know how long the new one will be
但是由于你标记了QC++,所以利用了动态可调整的
std::string
。std::string s = ".......";
std::string s1;
for(int i = 0; s[i] != '{'; i++)
{
if(s[i] != '\\' && s[i] != '?')
{
if(s[i] == '#')
s1 += '\\';
else
s1 += s[i];
}
}
关于c++ - 复制字符串中的所选字符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11357400/