[英]substr to char c++ no array
就像標題說的那樣,我正在嘗試將 substr 轉換為 char。 最終我想要做的是用 substr 告訴我是大寫還是小寫字母,我得到了提示,最好的方法是使用 ascii 值。 這就是我所擁有的
for(int i = 0; i<length; i++){
char a = a.substr(i,1);
if(a>=65&&a<=90){
uppercase++;
}
}
我在這里收到此錯誤:
string_info.cpp:34:16: error: member reference base type 'char' is not a
structure or union
char a = a.substr(i,1);
我明白它不起作用,因為 substr 輸出一個字符串而不是一個字符,但我不明白的是如何獲取這些 ascii 值。 有沒有人有任何想法?
為什么你甚至必須使用substr? 您的代碼基本上只是一個字符一個字符地走下字符串。 為此,您可以使用[]
或at
for (int i=0;i<a.length();i++) {
char c = a[i];
/*
Can also use
char c = a.at(i);
*/
if (c >= 'A' && c <= 'Z') {
uppercase++;
}
}
還要注意你的代碼char a = a.substr(i, 1);
是錯誤的,因為substr
返回一個string
,你也重新聲明a
。
我建議使用基於范圍的 for 循環,而不是使用 substr、at 或 operator[]:
std::string a = "Test";
int uppercase = 0;
for(const auto& c : a)
{
if (c >= 'A' && c <= 'Z')
uppercase++;
}
而不是使用 ASCII 值,最好使用 isupper 函數:
std::string a = "Test";
int uppercase = 0;
for (const auto& c : a)
{
if(isupper(c))
uppercase++;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.