[英]C++ Replace String Character with Character from Specific Index of Vector?
[英]Replace specific character in a string in C++
我有一个类似下面的代码-
Value = "Current &HT"; //this is value
void StringSet(const char * Value)
{
const char *Chk = NULL;
Chk = strpbrk(Value,"&");
if(Chk != NULL)
{
strncpy(const_cast<char *> (Chk),"&",4)
}
}
在上面的代码中,我想将Value中的“&”替换为“&amp。”。如果我拥有“&”单个字符,则可以正常工作,但在当前情况下strpbrk()返回“&HT”,而在下面的strncpy中,整个“&HT”被替换了。
现在,我想知道只能替换字符串中单个字符的方法。
您无法将C样式字符串中的一个字符替换为多个字符,因为您无法知道C样式字符串中有多少空间可用于添加新字符。 您只能通过分配新的字符串并将旧的字符串复制到新的字符串来做到这一点。 像这样
char* StringSet(const char* value)
{
// calculate how many bytes we need
size_t bytes = strlen(value) + 1;
for (const char* p = value; *p; ++p)
if (*p == '&')
bytes += 3;
// allocate the new string
char* new_value = new char[bytes];
// copy the old to the new and replace any & with &
char* q = new_value;
for (const char* p = value; *p; ++p)
{
*q = *p;
++q;
if (*p == '&')
{
memcpy(q, "amp", 3);
q += 3;
}
}
*q = '\0';
return new_value;
}
但这是可怕的代码。 您确实应该使用std :: string。
我认为您需要一些临时数组来保存&之后的字符串,然后在原始字符串中替换&并将临时数组附加到原始字符串。 这是上面修改的代码,我相信您可以使用strstr代替strchr,它接受char *作为第二个参数。
void StringSet(char * Value)
{
char *Chk = NULL,*ptr = NULL;
Chk = strchr(Value,'&');
if(Chk != NULL)
{
ptr = Chk + 1;
char* p = (char*)malloc(sizeof(char) * strlen(ptr));
strcpy(p,ptr);
Value[Chk-Value] = '\0';
strcat(Value,"&");
strcat(Value,p);
free(p);
}
}
感谢Niraj Rathi
您不应该修改常量字符串,当然也不能修改字符串文字。 尽管使用std::string
代替自己处理资源管理要好得多,但是一种方法是分配一个新的c样式字符串并返回一个指向它的指针:
char *StringSet(const char *Value) {
char buffer[256];
for (char *p = (char*)Value, *t = buffer; p[0] != 0; p++, t++) {
t[0] = p[0];
if (p[0] == '&') {
t[1] = 'a'; t[2] = 'm'; t[3] = 'p';
t += 3;
}
t[1] = 0;
}
char *t = new char[strlen(buffer)+1];
strcpy(t, buffer);
return t;
}
string str="Current &HT";
str.replace(str.find('&'),1,"&");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.