c - 使用向后 for 循环替换 C 中字符串的结尾
问题描述
我正在尝试使用 for 循环替换字符串的最后一部分,循环迭代原始字符串的每个元素,并将第一个(最后一个元素,因为我在 for 循环中向后迭代)元素分配给字符串scl = "SCL_10m.tif"
,其余的当计数器低于 15 时,从字符串中获取所有字符string
,并将它们分配给newString
. 然而最后的结果是:
The old string was: S2_2018_08_09_B02_10m.tif
The new string is S2_2018_08_09_B0old string:
这与我的预期结果不同:
The new string is S2_2018_08_09_SCL_10m.tif
我不知道那是怎么回事。它应该遍历所有元素,newString
因为它与原始字符串的大小相同。我检查了 C 中的一些替换字符串函数,但我想实现一些可以帮助我快速解决字符串问题中的特定替换子字符串的方法。
在C中处理String非常复杂,我还在学习一些关于它的理论,例如:null Byte等。来自 JavaScript、Python 和 Ruby,其中更多此类函数已在某些标准库中实现,我发现很难同时有助于了解如何从头开始实现此类算法以处理我的特定问题代码。我感谢任何关于以下代码中发生的事情的想法或提示:
/******************************************************************************
Replace last 11 characters in a longer string
by the values of a smaller (11-char long) string.
*******************************************************************************/
#include <stdio.h>
#include <string.h>
int main()
{
char *string;
string = "S2_2018_08_09_B02_10m.tif";
char *scl;
scl = "SCL_10m.tif";
int length = 0;
int length_scl = 0;
length_scl = strlen(scl);
length = strlen(string);
char newstring[length];
int i;
int cntr = length;
for (i = length; i >= 0; i--)
{
if(cntr > 15){
newstring[i] = scl[i];
cntr--;
}
else if(cntr <= 15)
{
newstring[i] = string[i];
}
}
printf("The old string was: %s\n", string);
printf("The new string is %s:\n", newstring);
return 0;
}
解决方案
char *func1(char *new, const char *src, const char *repl)
{
size_t src_len, repl_len;
if(src && repl)
{
src_len = strlen(src);
repl_len = strlen(repl);
if(src_len >= repl_len)
{
new[src_len] = 0;
while(repl_len)
{
new[--src_len] = repl[--repl_len];
}
if(src_len)
{
while(--src_len)
{
new[src_len] = src[src_len];
}
}
}
}
return new;
}
char *func2(char *new, const char *src, const char *repl, size_t nchars)
{
//last nchars only (inluding the nul char)
size_t src_len, repl_len;
if(new &&src && repl)
{
new[--nchars] = 0;
src_len = strlen(src);
repl_len = strlen(repl);
if(src_len >= repl_len)
{
while(repl_len && nchars)
{
new[--nchars] = repl[--repl_len];
--src_len;
}
if(src_len && nchars)
{
while(--src_len && --nchars)
{
new[nchars] = src[src_len];
}
}
}
}
return new;
}
int main()
{
char *string = "S2_2018_08_09_B02_10m.tif";
char *repl = "SCL_10m.tif";
char new[256];
printf("func1 - new = \"%s\", src = \"%s\", repl = \"%s\"\n", func1(new, string, repl), string, repl);
printf("func2 - new = \"%s\", src = \"%s\", repl = \"%s\"\n", func2(new, string, repl, 15), string, repl);
printf("func2 - new = \"%s\", src = \"%s\", repl = \"%s\"\n", func2(new, string, "123456789_SCL_10m.tif", 15), string, repl);
return 0;
}
推荐阅读
- nginx - 所有 ts 文件都没有记录在同一个 m3u8 文件中
- c - 相对于路径变量的 Eclipse 构建变量
- c - 比较两种初始化 int 指针的方法
- javascript - 如何按升序获取数组元素索引的位置?
- javascript - 单击另一个图像时更改图像
- google-cloud-platform - Certmanager 跨项目 DNS01 挑战失败
- c# - NuGet Msbuild Pack 与非 SDK 项目
- git - 使用 isomorphic-git 从 git remote 获取已更改文件的列表
- c# - 使用 Dapper 构建具有多对多关系的对象
- google-speech-api - 谷歌语音转文本