gpt4 book ai didi

c++ - 在不使用 C 字符串函数的情况下从 C 字符串中删除元音

转载 作者:行者123 更新时间:2023-12-01 14:14:57 28 4
gpt4 key购买 nike

我正在尝试从 userInput 数组中删除元音并将其余部分复制到 newString 数组。我认为遍历 userInput 并将其分配给 newStrin 会起作用,但我只获取 newString 数组的第一个字符。我可以看到在 i = 2 的迭代中,“t”应该分配给 newString[2],但是当我尝试在 main 中打印回数组时,它只打印第一个字符。

void removeVowels( char newString [], char userInput []){
int i = 0;
while ( i < myStrlen(userInput)) {
if ( (userInput[i] != 'a')&&
(userInput[i] != 'e')&&
(userInput[i] != 'i')&&
(userInput[i] != 'o')&&
(userInput[i] != 'u')){
newString[i] = userInput[i];
cout << newString[i] << endl;
}
i++;
}
}

我的输出:

c

t

cat without vowels is: c

预期输出:

c

t

cat without vowels is: ct

最佳答案

您唯一缺少的部分是跟踪写作地点

int writePos = 0; 

然后,将 newString[i] = userInput[i]; 替换为 newString[writePos++] = userInput[i]; ,这将在正确的位置写入,然后增加位置。

然后,相应地修复cout

正如@SalehMostafa 指出的那样,您也应该以 null 终止字符串,否则调用者将在最后读取垃圾。

newString[writePos] = 0; // at the end before returning

关于c++ - 在不使用 C 字符串函数的情况下从 C 字符串中删除元音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62886953/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com