C++(20):通过starts_with/ends_with检查字符串

322 篇文章 3 订阅 ¥199.90 ¥99.00

C++20提供了starts_with用于检查字符串是否以某个字符串开始,ends_with用于检查是否以某个字符串结束:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string str = "hello and 88";
    cout<<str.starts_with("hello")<<endl;
    cout<<str.starts_with("h")<<endl;
    cout<<str.starts_with("H")<<endl;
    cout<<str.ends_with("8")<<endl;
    cout<<str.ends_with("88")<<endl;
    cout<<str.ends_with(" 88")<<endl;
    return 0;
}

运行程序输出:

1

1

0

1

1

1

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
std::condition_variable.wait_for()是C++中std::condition_variable类的一个成员函数,用于在指定时间内等待条件变量满足特定条件。它的语法如下: ```cpp template< class Rep, class Period > std::cv_status wait_for( std::unique_lock<std::mutex>& lock, const std::chrono::duration<Rep, Period>& timeout_duration ); ``` 其中,`lock`是一个std::unique_lock<std::mutex>对象,用于保护条件变量。`timeout_duration`是一个std::chrono::duration对象,表示等待的时间段。 当调用std::condition_variable.wait_for()时,当前线程会被阻塞,直到以下情况之一发生: 1. 条件变量满足特定条件; 2. 等待时间超过了指定的时间段。 如果等待时间超过了指定的时间段,std::condition_variable.wait_for()会返回std::cv_status::timeout,表示等待超时。 以下是一个使用std::condition_variable.wait_for()的示例代码: ```cpp #include <iostream> #include <thread> #include <condition_variable> std::condition_variable cv; std::mutex mtx; bool ready = false; void worker() { std::this_thread::sleep_for(std::chrono::seconds(2)); std::unique_lock<std::mutex> lock(mtx); ready = true; cv.notify_one(); } int main() { std::cout << "Main thread starts." << std::endl; std::thread t(worker); std::unique_lock<std::mutex> lock(mtx); if (cv.wait_for(lock, std::chrono::seconds(1)) == std::cv_status::timeout) { std::cout << "Timeout occurred." << std::endl; } else { std::cout << "Condition variable is notified." << std::endl; } t.join(); std::cout << "Main thread ends." << std::endl; return 0; } ``` 在上面的示例中,主线程等待1秒钟,如果在1秒钟内没有收到通知,则输出"Timeout occurred.";如果在1秒钟内收到了通知,则输出"Condition variable is notified."。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风静如云

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值