这是我到目前为止所得到的:
void insert(char str1[], char str2[], int from, int to)
{
int i;
int j;
int location;
if(strlen(str2) < to-from+1) /* The space to put str2 in is bigger than str2 - or in other words - str2 is smaller than it (as in the statement */
{
location = from+strlen(str2)+1; /*the location needed to delete would be location to too because location equals to from added by str2 length (what will be replaced by the next, first loop) */
j = 0;
for (i = from ; i < to && j < strlen(str2) ; i++)
{
str1[i] = str2[j];
j++;
}
**for(i = location ; i <= to ; i++)
{
for(j = i ; j <= strlen(str1) ; j++)
{
str1[j] = str1[j+1]; /*every string character from i and above will get the value of the string character above her. if i was 3 then str1[3] will get the value of str1[4] and str1[4] will get the value of str1[5] and so...*/
}
}**
}
else if(strlen(str2) > to-from+1)
{
j = 0;
for (i = from ; i < to && j < strlen(str2) ; i++)
{
str1[i] = str2[j];
j++;
}
for(i = 0 ; i < strlen(str2)-(to-from+1) ; i++)
{
for(j = strlen(str1) ; j >= to+i ; j--)
{
str1[j] = str1[j-1];
}
}
}
else
{
j = 0;
for (i = from ; i < to && j < strlen(str2) ; i++)
{
str1[i] = str2[j];
j++;
}
}
}
问题在于大胆的部分(**) - 其他所有语句都有效,但如果它的语句是正确的那么它将无法工作,经过几次测试 - 现在我确定它在那里的某个地方是个问题。这都是我正在做的计算器,它是递归的,所以我需要替换字符串来解决函数的每次运行。有人能注意到问题吗?如果可以,请帮忙,非常感谢:)。
编辑: ** str1 =要插入的字符串。 ** str2 =您要插入的字符串
答案 0 :(得分:0)
例如使用memmove
#include <string.h>
char *insert(char str1[], char str2[], size_t from, size_t to){
size_t len1 = strlen(str1);
size_t len2 = strlen(str2);
if(from > to)
to = from;
if(len1 <= from && len1 <= to){
return strncpy(str1+len1, str2, len2+1);
}
if(len1 > from && len1 <= to){
return strncpy(str1+from, str2, len2+1);
}
len1 -= to;//strlen(str + to + 1) + 1('\0')
memmove(str1 + from + len2, str1 + to + 1, len1);
strncpy(str1 + from, str2, len2);
return str1;
}
答案 1 :(得分:0)
'location'是从'到'开始的str1,的其余部分应该去的地方。您当前的代码会将“位置+ 1”处的字符复制到“位置”。
如果你想用for循环来做,而不是使用memmove,第一部分应该是这样的:
location = from+strlen(str2); /* location where remainder of str1 must be shifted to */
j = 0;
for (i = from ; i < to && j < strlen(str2) ; i++)
{
str1[i] = str2[j];
j++;
}
for(i = to ; i <= strlen(str1) ; i++)
{
str1[location + i - to] = str1[i];
}
你可能想要将'改为'改为'改为+ 1',这取决于你的意图(如果要删除'或'的字符?)。