c - 使用连接查询字符串旋转程序。为什么不能完全发挥作用?
问题描述
我使用 C 编写了一个字符串旋转的代码。在下面给出的代码中,我将原始字符串复制到另一个变量上,并使用 strncat 函数来获取旋转到末尾的原始字符串的一部分。然后我声明了另一个字符串变量并复制了我们需要得到结果的连接字符串的字符。
#include <stdio.h>
#include <string.h>
void stringrotation(char *a,int rot)
{
char s[10];
char r[10]="";
strcpy(s,a);
strncat(s,a,rot);
printf("%s\n",s);
for(int i=rot; i<strlen(s);++i)
{
r[i-rot]=s[i];
}
printf("%s",r);
}
int main()
{
char *r="abcedef";
int rot=2;
stringrotation(r,rot);
}
此代码仅适用于变量 rot= 1,2 和 3 的值。我想知道为什么对其余值不起作用?任何人都可以提供使用类似技术的代码,但适用于所有字符串
解决方案
您的代码中有多个错误。潜在的堆栈溢出就是strlen(a) > 10
一个例子。此外,它不会产生正确的输出,因为rot
afterstrlen(a)-rot
中的字符不正确。
通常,C 中的字符串接口返回一个字符串作为返回值。它允许级联调用strfun1(strfun2(strfun3(...
工作。此外,用户可以决定如何处理该值,即如何呈现该值。
此外,让用户提供目标缓冲区以加快操作并减少内存消耗是一个好主意。
作为目的地传递NULL
可用于要求函数分配合适的缓冲区。free()
请记住在不再使用缓冲区时释放它以避免泄漏。
如果可能,memcpy()
请使用更优化的函数。
最终代码可能是:
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *stringrotation(const char *src, int rot, char *dst) {
size_t len = strlen(src);
// make sure that rotation makes sense
if (rot < 0 || rot >= len) return NULL;
// if no storade for output is provided, allocate it
if (dst == NULL) {
// allocated but for `len` characters and a terminator
dst = malloc(len + 1);
// check if allocation succeeded
if (!dst) return NULL;
}
// copy tail of the input to the output
memcpy(dst, src + rot, len - rot);
// concat head of the input to the output
memcpy(dst + len - rot, src, rot);
// add terminator to output
dst[len] = 0;
return dst;
}
int main()
{
char a[10];
stringrotation("abcdef", 2, a);
puts(a);
// reverse the first operation
char *b = stringrotation(a, 4, NULL);
puts(b);
free(b);
return 0;
}
印刷:
cdefab
abcdef
推荐阅读
- google-chrome - 如何为在不同主机但相同二级域上提供的 iframe 强制 Chrome 的“站点隔离”?
- cocoapods - 使用 Cocoapods 在 Pod Spec Test 的 App Host 中指定权利
- javascript - 防止 Javascript 重新排序 JSON
- jquery - 如果元素具有某个类,则防止事件触发
- git - git中的合并冲突问题
- ruby - 有没有一种内置的方法可以通过异常挖掘哈希和数组?
- python - 如何从核苷酸生成 IUPAC 代码?
- r - 无法上传最新的胶水包1.3.0
- r - 咕噜声,分组和过滤
- c - 在 qsort 中使用 strcmp() 比较字符串