编写宏函数来更改字符串的大小写?

Write a macro function to change the case of a string?

本文关键字:字符串 大小写 函数      更新时间:2023-10-16

//我试过这段代码

#include<iostream>
using namespace std;

转换字符的功能 字符串到相反大小写

#define case_change(str)
{
int ln = str.length();

根据 ASCII 值进行转换

#define for (int i=0; i<ln; i++)
{
#ifdef (str[i]>='a' && str[i]<='z'){
str[i] = str[i] - 32;
#endif}
//Convert lowercase to uppercase
#elifdef (str[i]>='A' && str[i]<='Z'){
str[i] = str[i] + 32;
#endif}
//Convert uppercase to lowercase

#endif}
}

驱动功能

int main()
{
string str = "GeEkSfOrGeEkS";
// Calling the Function
case_change(str);
cout << str;
return 0;
}

你似乎if了,ifdef困惑了。ifdef用于测试以前是否定义了宏,并基于该定义启用功能。请参阅此问题:#ifdef 和 #ifndef 的作用

相反,您正在尝试基于运行时测试执行特定代码段。为此,您需要if

如注释中所述,当您应该编写函数时,编写宏通常被认为是不好的做法。C 语言中的宏与函数

#ifdef (str[i]>='a' && str[i]<='z')

应该是

if (str[i]>='a' && str[i]<='z')

#ifdef没有意义,因为str[i]必须在运行时计算,而宏预处理器仅在编译时工作。

此外,#elifdef也不是合法的代币。出于与上述类似的原因,这应该else if

您可以使用此代码。我想它会帮助你

#include <iostream>
#include <bits/stdc++.h>

using namespace std;

#define CASE_CHANGE(str) ({        
int i = 0;                     
string op = "";                
while (str[i] != '') {       
if (isupper(str[i])) {     
op += tolower(str[i]); 
}                          
else {                     
op += toupper(str[i]); 
}                          
++i;                       
}                              
op;                            
})
int main() {
cout << CASE_CHANGE("babu");
}