【问题标题】:If statements that search to see if there are certain characters in them. c++If 语句用于搜索以查看其中是否有某些字符。 C++
【发布时间】:2020-10-01 19:06:26
【问题描述】:

我正在尝试编写两个 if 语句,它们将在字符串中搜索特定字符或验证字符是否为特定字母。

必须验证传递的信息是“s”还是“h”,如果不是,则将其设置为“s”。

另一个必须验证名称中是否包含逗号。数据以 Last, First 格式传递,如果缺少逗号,它将设置为“未知”

帮助入门? C++

【问题讨论】:

  • 所以我只是想出了字符串。我只需要关于 's' 和 'h' 的 if 语句的帮助

标签: c++ string if-statement char


【解决方案1】:

我将假设您定义并初始化了一个名为 str 的字符串。

string str = "something here";

第一个 if 语句如下所示

char &temp = str[0]; // temp is a reference to a character within the string
if(temp == 's'){
    cout << "current character is s" << endl;
}
else if(temp == 'h'){
    cout << "current character is h" << endl;
    temp = 's';
}

第二个需要一个for循环来检查字符串中的每个字符。

bool found = false;
for(char item : str){
    if(item == ','){
         cout << "Found a comma" << endl;
         found = true;
         break;
    }
}

if(found == false){
    str = "Unknown";
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    • 2018-06-23
    • 2015-05-29
    相关资源
    最近更新 更多