长度函数:
int length(const char s[])
{
int length = 0;
while(s[length]!='\0')
{
length++;
}
return length;
}
插入功能:
void insert(char s1[], const char s2[], int n)
{
char *beginOfString = s1;
int lengthOfS1 = length(s1);
int lengthOfS2 = length(s2);
char s1Copy[lengthOfS1 + lengthOfS2];
int c, afterC, lengthOfRemainingPart;
c = 0;
c = n + 1;
beginOfString += c;
afterC = c; //nth position to start from to add onto array
lengthOfRemainingPart = length(beginOfString);
c = 0;
int counter = 0;
for(c = 0; c < length(s1) - 1; c++) {
s1Copy[c] = s2[counter];
for(c = afterC; c < (lengthOfS1 + lengthOfS2) - 1; c++) {
if(c == afterC) {
s1Copy[c] = s2[counter];
} else {
counter++;
if(s2[counter] != *"\0")
s1Copy[c] = s2[counter];
}
}
}
c = 0;
for(c = 0; c < length(s1Copy) - 1; c++) {
printf("\n %c \n", s1Copy[c]);
}
printf("\n");
printf("\n %s \n", beginOfString);
printf("\n %s \n", "LINE");
}
函数调用(及相关声明):
#define MAX_STR 20
char ab[MAX_STR + 1] = "Chicken and Chips";
char b[MAX_STR + 1] = "Scampi";
insert(ab, b, 7);
我正在尝试将char数组插入到另一个char数组中,同时保持其余的字符仍然在数组中,但是根据用户想要根据n值插入char数组的位置进行移位。
这似乎不起作用,似乎输出错误的值。函数调用和函数头(参数类型等)需要保持我的方式。只有功能体本身才能改变。
输出应为“ChickenScampi and Chips”
我出错的任何想法?干杯。
答案 0 :(得分:4)
不要涂糖衣。这段代码很乱。如果您只是
,那么您想要完成的任务最简单s1[]
复制到您的目标。s2[]
附加到目标。s1[min(n, lengthS1)]
通过s1[lengthS1]
附加到目标。最重要的是,目标必须能够容纳两个字符串和一个nulchar终结符,目标缓冲区不会这样做(它只有一个字符)
不需要嵌套的for循环。无论你是在走自己的索引变量,它都会被打破。
#include <stdio.h>
size_t length(const char s[])
{
const char *end = s;
while (*end)
++end;
return end - s;
}
void insert(const char s1[], const char s2[], int n)
{
size_t lengthOfS1 = length(s1);
size_t lengthOfS2 = length(s2);
size_t pos = (n < lengthOfS1) ? n : lengthOfS1;
size_t i;
// declare VLA for holding both strings + terminator
char s1Copy[lengthOfS1 + lengthOfS2 + 1];
// put in part/full s1, depending on length
for (i=0; i<pos; ++i)
s1Copy[i] = s1[i];
// append s2
for (i=0; i<lengthOfS2; ++i)
s1Copy[pos+i] = s2[i];
// finish s1 if needed.
for (i=pos; i<lengthOfS1; ++i)
s1Copy[i+lengthOfS2] = s1[i];
// termiante string
s1Copy[lengthOfS1 + lengthOfS2] = 0;
puts(s1Copy);
}
int main()
{
char ab[] = "Chicken and Chips";
char b[] = "Scampi";
insert(ab, b, 0);
insert(ab, b, 7);
insert(ab, b, 100);
}
<强>输出强>
ScampiChicken and Chips
ChickenScampi and Chips
Chicken and ChipsScampi
<强>摘要强>
如果您不确定发生了什么,那么您应该做的 last 事情就是编写更多代码。相反,停止编码,获取一些纸张和书写工具,并重新考虑问题。