我基本上是在创建一个小方法/函数,如果字符串的长度比输入的 new_line 长,它会剪切该字符串。但是,我有两个不同的版本。
第一个代码计算字符串的长度并在相同的方法/函数下将其全部缩短。
第二个代码具有单独的函数用于长度计算和修剪字符串。
第一个代码不起作用(它不修剪字符串)而第二个代码起作用。我不知道为什么。 谢谢
无效的代码
void shorten(char *s, int new_len){
int len = 0;
while(*s){
len++;
s++;
}
while( len > new_len){
s[len - 1] = '\0';
s--;
len--;
}
}
有效的代码
int length(char *s){ // count length of string
int len = 0;
while(*s){
len++;
s++;
}
return len;
}
void shorten(char *s, int new_len) {
int len = length(s);
while( len > new_len){
s[len - 1] = '\0';
s--; // move to previous char
len--; // decrease length
}
}
最佳答案
您正在通过 s++;
更改函数参数,在第一个循环之后不再指向字符串的开头。
也许您想这样做:
void shorten(char *s, int new_len){
int len = 0;
while(*s){
len++;
s++;
}
while( len > new_len){
s--;
len--;
*s = '\0';
}
}
此外,建议对所有大小/长度/索引相关操作使用size_t
。
关于C: 如果没有单独的功能,代码将无法工作。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52912284/