我正在尝试使用指针从一串二维数组中删除元音。我能够通过元音的 ASCII 值检测到元音,但字符串没有得到更新。
这部分代码不能更改。
void remove_vowel(char strings[NUM_STRINGS][STRING_LENGTH])
我的代码哪里出错了?
更新后的代码:
void remove_vowel(char strings[NUM_STRINGS][STRING_LENGTH])
{
// loop through each row, starting intitally points to last element
for (char(*p)[STRING_LENGTH] = strings; p != strings + NUM_STRINGS; ++p) {
// variable q points to the first element
for (char *q = *p; q != *p + STRING_LENGTH; ++q) {
if (*q != 'a' && *q != 'e' && *q != 'i' && *q != 'o' && *q != 'u') {
//printf("%c",*q);
*q = *q;
}
}
}
}
我能够使用下面列出的解决方案重写代码。感谢大家的帮助!
解决方案
void remove_vowel(char strings[NUM_STRINGS][STRING_LENGTH])
{
// store the array in a pointer
char(*wordHolder)[STRING_LENGTH] = strings;
// loop through each row
for (int i = 0; i < NUM_STRINGS; i++)
{
// assign worl
char *letter = *wordHolder;
char *dest = *wordHolder;
// check if null character
while (*letter != '\0') {
// check for vowels
if (*letter != 'a' && *letter != 'e' && *letter != 'i' && *letter != 'o' && *letter != 'u') {
// assign non-vowel letter to destination
*dest++ = *letter;
}
// move to next letter
letter++;
}
// add null pointer to end of destination
*dest = '\0';
// increment pointer position to next word
wordHolder++;
}
}
最佳答案
让我们考虑一个等效的 C 语言。
在 C 语言中,您需要将文本视为数组。对于数组,当您删除一个插槽时,您需要移动剩余的项目以覆盖已删除的插槽。
让我们从这里开始。
void dont_copy_vowels(char text_array[STRING_LENGTH])
{
char * p_source = &text_array[0];
char * p_destination = &text_array[0];
const unsigned int length = strlen(text_array);
while (*p_source != '\0')
{
static const char vowels[] = "aeiou";
if (strchr(vowels, *p_source) != NULL)
{
++p_source;
continue; // don't copy vowels.
}
// Copy the letter or symbol.
*p_destination++ = *p_source++;
}
*p_destination = '\0';
}
由于您使用的是 C 风格字符串数组,因此您需要将上述代码放入一个循环中:
for (unsigned int string_index = 0;
string_index < NUMBER_OF_STRINGS;
++string_index)
{
dont_copy_vowels(strings[string_index]);
}
关于c - 在 C 中使用指针从字符串中删除元音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42206871/