patterncMinor
Function to return last line's length of a string
Viewed 0 times
lastlinereturnlengthfunctionstring
Problem
I am completely re-writing the textbox GUI widget.
In order to set the position cursor after the last character in the last line of a text, it is good if you know the exact column of it. So I created a small function that calculates this. It is meant to work sonicly.
In order to set the position cursor after the last character in the last line of a text, it is good if you know the exact column of it. So I created a small function that calculates this. It is meant to work sonicly.
int get_last_line_length (char *string)
{
const int len = strlen(string) - 1;
int i;
for(i = len; i != -1 && string[i] != '\n'; i--);
return (len - i);
}Solution
It's good that you've used
Anyway, a bit of a review:
strlen, but there's actually another standard function that could be useful here. Instead of your reverse loop, you can use strrchr to find a pointer to the last occurrence of a character (or NULL if said character is not found). As discussed in the comments, this could be (and likely is) slower in the case when a newline is not found, but unless this function is called very often or is in a very performance critical path, I can't imagine it will be an issue. If you do need to optimize it to your original implementation, I would pull the reverse loop logic out into a function.Anyway, a bit of a review:
- Your
stringparameter should be a pointer to const since it's not modified.
- Personal style thing: I'm not a fan of
return (...). If it matters, it also tends to be pretty rare style wise in C.
- You should probably explicitly document what happens if a line break is not found in the text. I wouldn't be sure whether
strlen(string)or -1 should be returned.
Context
StackExchange Code Review Q#94840, answer score: 9
Revisions (0)
No revisions yet.