如何打印字符串的第一个单词 [英] How to print the first word of a string

查看:242
本文介绍了如何打印字符串的第一个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助

标题说明了这一切

如何打印字符串的第一个单词



我尝试过:



没什么,不知道标题

只需要一些帮助这里

Please Help
The title says it all
How can i print the first word of a string

What I have tried:

Nothing, don't know The title
Just need some help here

推荐答案

首先,决定什么使一个词结束?这是一个空间?是的 - 但是这个回复的第一个字并不以一个结尾,这句话的最后一个字也没有!或这个。 (并且这个不是从一个单词开始。)本段中的3个句子不是!



因此,首先要确定定义单词的内容:'一系列以非字母字符结尾的大写和/或小写字母'



用它排序后,解析你的字符串:忽略任何不是一封信,然后开始你的话。这是一个字,直到你找到一个非字母字符,然后你可以打印它。



试一试 - 如果你想一想就不难几分钟。

提示:首先编写一个以字符作为参数的函数,并根据它是否为单词字符返回true或false。
First, decide what makes a word "end"? It is a space? Well yes - but the first word of this reply doesn't end with one, and neither does the last word of this sentence! Or this. (And this one doesn't start with a word.) 3 of the sentences in this paragraph don't!

So start by deciding what defines a "word": 'a sequence of upper- and / or lower- case letters that end with a non-alphabetic character'

With that sorted, parse your string: ignore anything that isn't a letter, then start your word. It's a word until you reach a non-letter character, and you can then print it.

Give it a try - this isn't difficult if you think about it for a few minutes.
Hint: start by writing a function that takes a character as a parameter, and returns true or false depending on if it's a "word character" or not.


这实际上取决于您的要求中'word'的确切定义。对于简单的场景, istringstream 就足够了:

It really depends on the exact definition of 'word' in your requirements. For simple scenarios a istringstream is just enough:
#include <iostream>
#include <sstream>
using namespace std;

int main()
{
  string str = "foo bar foobar";
  istringstream iss(str);
  string first_word;
  iss >> first_word;
  cout << "first word of '" << str << "' is '" << first_word << "'" << endl;
}


这篇关于如何打印字符串的第一个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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