我正在尝试实现一种简单安全的方法来修剪前后两个空格的char数组。它可以删除开头的空格,但不适用于另一侧。谁能看到我在做什么错?这是我的代码:
template<size_t charCount>
void strtrim_safe( char (&output)[charCount] ) {
char *ptr = output;
size_t n = charCount;
size_t start = 0;
size_t end = 0;
// Find the start and end position of trimmed string
while ( n-- != 0 && *ptr != 0 ) {
if ( *ptr == 32 ) {
if ( end == 0 ) {
start++;
} else {
break;
}
} else {
end++;
}
ptr++;
}
// Shift the char array
for ( int i = start, j = 0; i < end, j < charCount; i++, j++ ) {
output[j] = output[i];
}
}
Run Code Online (Sandbox Code Playgroud)
提前致谢!
EDIT1:感谢您的输入,我认为我已经解决了该问题。以下代码代替Shift char数组下的代码似乎可以解决问题:
// Shift the char array
for ( int i = start, j = 0; i < end + start && j < charCount; i++, j++ ) {
output[j] = output[i];
}
output[end] = 0;
Run Code Online (Sandbox Code Playgroud)
仅使用尾随空白进行测试,仅使用前导空白进行测试,两侧均使用空白,当然也没有空白。到目前为止,一切都很好
EDIT2:为了解决可能的内部空间,我在while循环中进行了检查,并提出了以下建议:
template<size_t charCount>
void strtrim_safe( char (&output)[charCount] ) {
char *ptr = output;
size_t n = charCount;
size_t start = 0;
size_t end = 0;
// Find the start and end position of trimmed string
while ( n-- != 0 && *ptr != 0 ) {
if ( *ptr == 32 ) {
if ( end == 0 ) {
start++;
} else {
size_t endTmp = end;
while ( *ptr == 32 && n-- != 0 && *ptr != 0 ) {
end++;
ptr++;
}
if ( *ptr == 0 || n == 0 ) {
end = endTmp;
} else {
end++;
}
}
} else {
end++;
}
ptr++;
}
// Shift the char array
for ( int i = start, j = 0; j < end + start && j < charCount; i++, j++ ) {
output[j] = output[i];
}
output[end] = 0;
}
Run Code Online (Sandbox Code Playgroud)
void strtrim(char* str) {
int start = 0; // number of leading spaces
char* buffer = str;
while (*str && *str++ == ' ') ++start;
while (*str++); // move to end of string
int end = str - buffer - 1;
while (end > 0 && buffer[end - 1] == ' ') --end; // backup over trailing spaces
buffer[end] = 0; // remove trailing spaces
if (end <= start || start == 0) return; // exit if no leading spaces or string is now empty
str = buffer + start;
while ((*buffer++ = *str++)); // remove leading spaces: K&R
}
Run Code Online (Sandbox Code Playgroud)