Reputation: 145
I'm basically creating a small method/function that cuts a string if its length is longer than the input new_line. However, I have two different version of this.
The first code calculates the length of the string and shortens it all under the same method/function.
The second code has separate functions for both length calculation and trimming the string.
The first code does not work (it does not trim the string) while the second one does work. I don't know why though. Thanks
The code that does not work
void shorten(char *s, int new_len){
int len = 0;
while(*s){
len++;
s++;
}
while( len > new_len){
s[len - 1] = '\0';
s--;
len--;
}
}
The code that works
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
}
}
Upvotes: 1
Views: 81
Reputation: 4641
What you need to do is not increment the s
pointer when calculating the length. Also, you can avoid the while loop to reset the length by just setting s[new_len] = '\0'
if len > new_len
.
Also, since strlen()
returns length of type size_t
, it is advisable to use size_t
for storing length of the char string (it could eliminate any warnings related to comparison between signed and unsigned values).
void shorten(char *s, size_t new_len) {
size_t len = 0;
while (s[len] != '\0') {
len++;
}
/*while ( len > new_len) {
s[len - 1] = '\0';
len--;
}*/
if (len > new_len) {
s[new_len] = '\0';
len = new_len;
}
}
Upvotes: 0
Reputation: 903
You are altering the function argument by doing s++;
, which after the first loop is no longer pointing to the start of the string.
Perhaps you wanted to do this:
void shorten(char *s, int new_len){
int len = 0;
while(*s){
len++;
s++;
}
while( len > new_len){
s--;
len--;
*s = '\0';
}
}
Also, it is advisable to use size_t
for all the size/length/index related operation.
Upvotes: 2