我们被要求创建一个程序,除了小字母和空格(使用指针)之外,它将删除给定字符串中的任何字符。
例:
输入一个字符串:您好有#20个标记指向NORTH。
输出:我有标记指向
这是我到目前为止所得到的:
#include <iostream> #include <cstring> #include <cctype> void lowerCase(char *text); int main() { char str[100]; std::cout << "Enter a string: "; std::cin.getline(str, 100); lowerCase(str); std::cout << "\nOutput after lowerCase():\n"; std::cout << str; system("pause>0"); return 0; } void lowerCase(char *text) { while (*text != '\0') { if (((unsigned int)*text >= 97 && (unsigned int)*text <= 122) || *text == ' ') { text++; } else { for (char *i = text; *i != '\0'; i++) { *i = *(i + 1); } text++; } } }此代码的输出为:
输入一个字符串:您好有#20个标记指向NORTH。
lowerCase()之后的输出:
我有2个标记点到OT。
如何在示例中实现结果?
We were asked to create a program that will remove any characters from the given string except the small letters and white space (using pointers).
Example:
Enter a String: Hi there are #20 markers points to NORTH.
Output: i there are markers points to
This is what I got so far:
#include <iostream> #include <cstring> #include <cctype> void lowerCase(char *text); int main() { char str[100]; std::cout << "Enter a string: "; std::cin.getline(str, 100); lowerCase(str); std::cout << "\nOutput after lowerCase():\n"; std::cout << str; system("pause>0"); return 0; } void lowerCase(char *text) { while (*text != '\0') { if (((unsigned int)*text >= 97 && (unsigned int)*text <= 122) || *text == ' ') { text++; } else { for (char *i = text; *i != '\0'; i++) { *i = *(i + 1); } text++; } } }This code has an output of:
Enter a String: Hi there are #20 markers points to NORTH.
Output after lowerCase():
i there are 2 markers points to OT.
How can I achieve the result in the example?
最满意答案
你的函数lowerCase()跳过应删除的连续字符; 如果你在逻辑上跟踪else块,你可以看到这个:
else { for (char *i = text; *i != '\0'; i++) { *i = *(i + 1); } text++; // <- this always skips the next character }因为*i = *(i + 1)已经将下一个字符复制到text指向的位置,所以在else-block中不需要text++ 。
Your function lowerCase() leapfrogs over consecutive characters that should be removed; you can see this if you logically trace through the else-block:
else { for (char *i = text; *i != '\0'; i++) { *i = *(i + 1); } text++; // <- this always skips the next character }You don't need text++ in the else-block since *i = *(i + 1) already copies the next character into the position pointed to by text.
更多推荐
发布评论