c++对cstring数组中特殊字符的测试

C++ testing for special character in cstring array

本文关键字:特殊字符 测试 数组 cstring c++      更新时间:2023-10-16

我有一个C字符串数组:

char test[6] = {'n', 't', 'e', 's', 't', ''}

我想测试字符串是否以空白字符(n, t, r)开始,如果是,重新排列数组,以便将非空白字符移到数组的前面,并为每个需要删除的空白字符将cstring缩短1。

那么如果我从一个字符串开始,看起来像:

n, t, t, e, s, t, 
or
r, t, e, s, t, 

在函数之后,两个数组看起来像:

t, e, s, t, 
t, e, s, t, 

我有两个问题。第一个是特殊字符的条件测试没有正常工作

int idx = 0;
if (test[idx] != 'n' || test[idx] != 'r' || test[idx] != 't')
    return;

即使它是以其中一个特殊字符开头,也会返回。

然而,这似乎也已经需要重大改进。

之后,我不确定如何剪辑字符串。例如,如果字符串以空白字符开头,我基本上需要删除该字符,向上移动其他字符,并每次将字符串缩短一个。

基本上,我正在为如何做到这一点的逻辑而挣扎。

任何和所有的帮助都是非常感激的。提前感谢!

为什么不将指针向前递增,直到找到一个非空白字符?

char* cstr = test;
while (*cstr && (*cstr == 'n' || *cstr == 'r' || *cstr == 't'))
    ++cstr;

您编写的测试是检查该字符是否不等于任何空白字符。你需要检查它是不是等于所有的。你想要的:

int idx = 0;
if (test[idx] != 'n' && test[idx] != 'r' && test[idx] != 't')
    return;

那么,假设idx是第一个非空白字符的索引,或者是空终止符,您可以像这样缩短字符串:

int i;
for (i = 0; test[idx+i] != ''; i++)
    test[i] = test[idx+i];
test[i] = '';

正如其他人所说,使用isspace()和指针有更优雅的方法来完成所有这些,但这应该给您一个基本的想法。

首先,使用isspace代替,它将使代码更简单,并确保代码找到您没有想到的空白字符。

第二,如果您必须使用char[]或必须实际删除空白,那么您将不得不做更多的工作。如果你所需要的只是一个指向字符串开头的指针,那就容易多了。这些字符仍然在内存中,但如果使用指针,它们将不会出现在字符串的开头。

char test[] = "ntest";
char *test_ptr = test;
while (*test_ptr && isspace(*test_ptr)) {
    ++test_ptr;
}
/*test_ptr now points to the first non-whitespace character in test, or the NULL character at the end of the string if it was all whitespace.*/

如果你需要这个字符串在char数组本身的开头,你可以在上面的代码之后使用memmove来移动字符串(strcpy不起作用,因为范围重叠):

/* to be placed after block of code above */
memmove(test, test_ptr, strlen(test)-(test_ptr-test)+1); /* +1 for NULL not automatically copied with memmove */
/* test[0] is now the first non-whitespace character or NULL */

或者因为你正在使用c++,你可以走std::string路线:

std::string test = "ntest";
size_t start_pos = test.find_first_not_of("rnt");
if (start_pos != std::string::npos) {
    test = test.substr(start_pos, std::string::npos);
} else {
    test = "";
}
//test now contains no whitespace in the beginning