如何在字符串中搜索字符? [英] How can I search for a character in a string?

查看:113
本文介绍了如何在字符串中搜索字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序,将短日期(mm / dd / yyyy)转换为长日期(2014年3月12日),并打印出日期。

I'm writing a program that converts a short date (mm/dd/yyyy) to a long date (March 12, 2014) and prints out the date.

由于以下用户输入,程序必须工作:
10/23/2014
9/25/2014
12 / 8/2015
1/1/2016

The program has to work given the following user inputs: 10/23/2014 9/25/2014 12/8/2015 1/1/2016

我有程序使用第一个用户输入,但我不知道如何继续处理用户输入在字符串的第一个位置没有0。

I have the program working with the first user input but I'm not sure how to proceed with handling a user input that doesn't have a "0" in the first position of the string.

#include <iostream>
#include <string>

using namespace std;

int main() 
{
    string date; 
    cout << "Enter a date (mm/dd/yyyy): " << endl;
    getline(cin, date);

    string month, day, year;

    // Extract month, day, and year from date
    month = date.substr(0, 2);
    day = date.substr(3, 2);
    year = date.substr(6, 4);

    // Check what month it is 
    if (month == "01") {
        month = "January";
    }
    else if (month == "02") {
        month = "February";
    } 
    else if (month == "03") {
        month = "March";
    } 
    else if (month == "04") {
        month = "April";
    } 
    else if (month == "05") {
        month = "May";
    } 
    else if (month == "06") {
        month = "June";
    } 
    else if (month == "07") {
        month = "July";
    } 
    else if (month == "08") {
        month = "August";
    } 
    else if (month == "09") {
        month = "September";
    } 
    else if (month == "10") {
        month = "October";
    } 
    else if (month == "11") {
        month = "November";
    } 
    else {
        month = "December";
    }

    // Print the date
    cout << month << " " << day << "," << year << endl;
    return 0;
}

我非常感谢任何帮助。

推荐答案

正如红蛇在评论中写道:使用 std :: string :: find ,例如

As Red Serpent wrote in the comments: Search for the / using std::string::find, e.g.

#include <iostream>

int main()
{
    std::string date = "09/28/1983";

    int startIndex = 0;
    int endIndex = date.find('/');
    std::string month = date.substr(startIndex, endIndex);

    startIndex = endIndex + 1;
    endIndex = date.find('/', endIndex + 1);
    std::string day = date.substr(startIndex, endIndex - startIndex);

    std::string year = date.substr(endIndex + 1, 4);

    std::cout << month.c_str() << " " << day.c_str() << "," << year.c_str() << std::endl;

    return 0;
}

这篇关于如何在字符串中搜索字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆