我有一個trans函式,它使用單個引數,必須為空,并通過c從main.
Example:
input: dOgdoG
output: DoGDOg
該函式確實改變了大小寫,但我無法想出一種方法來構建新詞/替換舊詞,因為我不斷收到有關“const char”或“無效轉換”的編譯錯誤。
以下程式給出錯誤“從char到的無效轉換const char*
我只是出于示例目的更改了函式的型別。
#include <iostream>
#include <cstring>
#include <fstream>
using namespace std;
char trans(char c)
{
if(c >= 'a' && c <= 'z')
return c-32;
else
if(c >= 'A' && c <= 'Z')
return c 32;
}
int main()
{
char s[101], s2[101] = "";
cin >> s;
int i;
for(i=0; i<strlen(s); i )
{
strncat(s2, trans(s[i]), 1);
}
cout<<s2;
return 0;
}
編輯:我從char函式更改為void函式并洗掉了for.
void trans(char c)
{
if(c >= 'a' && c <= 'z')
c-=32;
else
if(c >= 'A' && c <= 'Z')
c =32;
}
int main()
{
char s[101], s2[101] = "";
cin >> s;
int i;
for(i=0; i<strlen(s); i )
{
/// i dont know what to put here
}
cout<<s2;
return 0;
}
uj5u.com熱心網友回復:
不要重新發明輪子。標準庫具有識別大小寫字母和改變大小寫的功能。使用它們。
char trans(char ch) {
unsigned char uch = ch; // unfortunately, character classification function require unsigned char
if (std::isupper(uch))
return std::tolower(uch);
else
return std::toupper(uch);
}
您可能傾向于將該else分支更改為else if (std::islower(uch) return std::toupper(uch); else return uch;,但這不是必需的;std::toupper僅將小寫字母更改為大寫字母,因此不會影響非小寫字符。
然后,當你呼叫它時,只需復制結果:
int i = 0;
for ( ; i < strlen(s); i)
s2[i] = tran(s[i]);
s2[i] = '\0';
編輯:
由于似乎需要以艱難的方式做事,讓我們更改trans以匹配:
void trans(char& ch) {
unsigned char uch = ch; // unfortunately, character classification function require unsigned char
if (std::isupper(uch))
ch = std::tolower(uch);
else
ch = std::toupper(uch);
}
現在,您可以將其應用到位:
for (int i = 0; i < strlen(s); i)
trans(s[i]);
我稱之為“艱難的方式”,因為使用原始版本trans您可以直接使用它來修改原始字串:
for (int i = 0; i < strlen(s); i)
s[i] = trans(s[i]);
你可以用它來復制字串:
for (int i = 0; i < strlen(s); i)
s2[i] = trans(s[i]);
// don't forget the terminating nul
通過參考傳遞,只能就地修改;復制需要一個額外的步驟:
strcpy(s2, s1);
for (int i = 0; i < strlen(s); i)
trans(s2[i]);
uj5u.com熱心網友回復:
strncat以 2 個字串和一個數字作為引數;您的第二個引數是 a char,而不是字串。
uj5u.com熱心網友回復:
您可以std::transform與字串實用函式一起使用,例如std::isupper,std::toupper并且類似地用于小寫。因為,問題被標記C std::string對于字串,優先于const char*1。
#include <string>
#include <cctype>
#include <iostream>
#include <algorithm>
char trans(unsigned char c){
if (std::isupper(c))
return std::tolower(c);
else if (std::islower(c))
return std::toupper(c);
else
return c;
}
int main(){
std::string s = "dOgdoG12";
std::string out;
out.resize(s.length());
std::transform(s.begin(), s.end(), out.begin(), trans);
std::cout << out; // DoGDOg12
}
演示
1. 所以在vs 上發帖char*std::string
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/370903.html
