我试图在C中编写将采用字符串的代码,检查每个字符是否为特定字符(称之为'x'
),如果字符为'x'
,则更改它多个字符(如"yz"
)。这是我的尝试,假设缓冲区和替换是定义的字符数组(即char buffer[400] = jbxyfgextd...; char replace[250];
)
int j = 0;
for (j = 0; j < 110; j++) {
if (buffer[j]=='x') {
int len = strlen(replace);
replace[len] = 'y';
replace[len+1] = 'z';
}
else {
replace[j]=buffer[j];
}
}
当我运行此功能时,我会收到一些y
和z
,但它们并非背靠背。是否有任何程序/功能可以轻松完成这项工作?
答案 0 :(得分:2)
因为buffer[]
和replace[]
数组中的索引不相同。分别使用两个索引。
在您的代码表达式中:replace[j] = buffer[j];
错误。你可以纠正它:
else {
int len = strlen(replace);
replace[len]=buffer[j];
}
但要使用strlen()
,数组replace[]
应该以nul \0
终止。 (声明替换为char replace[250] = {0}
)
修改:
要编写更好的代码,请使用上面建议的两个septate索引 - 代码将高效且简化。
int bi = 0; // buffer index
int ri = 0; // replace index
for (bi = 0; bi < 110; bi++) {
if (buffer[bi] == 'x') {
replace[ri++] = 'y';
replace[ri] = 'z';
}
else {
replace[ri] = buffer[bi];
}
replace[++ri] = '\0'; // terminated with nul to make it string
}
答案 1 :(得分:0)
#include <iostream>
#include <string>
#include <cstring>
int main ( int argc, char *argv[])
{
// Pass through the array once counting the number of chars the final string
// will need then allocate the new string
char buffer[] = "this x is a text test";
char replacement[] = "yz";
unsigned int replaceSize = strlen(replacement);
unsigned int bufferSize = 0;
unsigned int newSize = 0;
// calculate the current size and new size strings
// based on the replacement size
char *x = buffer;
while (*x)
{
if ( *x == 'x' )
{
newSize+=replaceSize;
}
else
{
++newSize;
}
++x;
++bufferSize;
}
// allocate the new string with the new size
// and assign the items to it
char *newString = new char[newSize];
unsigned int newIndex = 0;
for ( unsigned int i = 0; i < bufferSize; ++i )
{
if ( buffer[i] == 'x' )
{
for ( unsigned int j = 0; j < replaceSize ; ++j )
{
newString[newIndex++] = replacement[j];
}
}
else
{
newString[newIndex++] = buffer[i];
}
}
std::string originalS ( buffer );
std::string newS ( newString );
std::cout << "Original: " << originalS << std::endl;
std::cout << "New: " << newS << std::endl;
delete newString;
}