使用C

编程入门 行业动态 更新时间:2024-10-08 02:18:15
使用C-String和指针。(Using C-String and Pointers. Remove any characters except small cases and whitespaces)

我们被要求创建一个程序,除了小字母和空格(使用指针)之外,它将删除给定字符串中的任何字符。

例:

输入一个字符串:您好有#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.

更多推荐

本文发布于:2023-08-02 08:10:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1372668.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!