【问题标题】:Lowercasing Capital Letters in char array[] in C++ through Pointers通过指针在 C++ 中的 char 数组 [] 中小写大写字母
【发布时间】:2018-05-10 17:05:10
【问题描述】:

我正在尝试使用指针将所有大写字母递归小写

使用 C++ 编程语言。下面是sn-p的代码:

// Example program
#include <iostream>
#include <string>
using namespace std;

void all_lower(char* input) {

    if ( *input ) {
        cout << input << endl;
        return;
    }

    if ( *input >= 'A' && *input <= 'Z') {    
       *input += 32; // convert capital letter to lowercase
    }
    cout << *input << endl;

    all_lower(++input); // simply move to next char in array
}

int main() {
   char test[] = "Test";
   all_lower(test);
   return 0;
}

输出结果是:

“测试”

即使我尝试将元素的 ASCII 码值增加 32。

【问题讨论】:

  • 我认为您实际上使用的是 C++,而不是 C。
  • 你是对的,对不起。我很困惑。

标签: c++ pointers void-pointers


【解决方案1】:

您将在检测到的第一个非空字符'T' 上退出函数,然后在退出之前输出整个数组,因此您看到的是原始未修改的输入。您根本没有在数组中递归。您需要遍历数组,直到到达空终止符。

你需要改变这个:

if ( *input ) {
    cout << input << endl;
    return;
}

改为:

if ( *input == 0 ) {
    return;
}

然后该功能将按预期工作。

话虽如此,我建议您从函数中删除cout 语句,并在函数退出后在main() 中执行单个cout。这会加快函数的运行速度,并证明test[]数组的内容实际上正在被修改:

#include <iostream>
using namespace std;

void all_lower(char* input)
{
    if ( *input == 0 ) {
        return;
    }

    if ( *input >= 'A' && *input <= 'Z') {    
       *input += 32; // convert capital letter to lowercase
    }    

    all_lower(++input); // simply move to next char in array
}

int main()
{
   char test[] = "TEST";
   cout << "Before: " << test << endl;
   all_lower(test);
   cout << "After: " << test << endl;
   return 0;
}

Live Demo

而且,由于您使用的是 C++,请考虑完全删除 all_lower() 并改用 STL std::transform() 算法:

#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
   char test[] = "TEST";
   cout << "Before: " << test << endl;
   transform(test, test+4, test, [](char ch){ return tolower(ch); });
   cout << "After: " << test << endl;
   return 0;
}

Live Demo

【讨论】:

    【解决方案2】:

    简短易懂:

    #include <iostream>
    #include <string>
    using namespace std;
    
    void all_lower(const char* input) {
        if (!*input) {
            std::cout << std::endl;
            return;
        }
        std::cout << (char)(std::isalpha(*input) ? tolower(*input) : *input);
        all_lower(++input); // simply move to next char in array
    }
    
    int main() {
       all_lower("Test");
       return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2023-02-09
      • 1970-01-01
      • 1970-01-01
      • 2017-11-12
      • 1970-01-01
      • 2012-12-09
      • 1970-01-01
      • 2013-04-14
      • 1970-01-01
      相关资源
      最近更新 更多