如何使用 StreamTokenizer 确保特定标记之间有空格?

发布于 2024-10-28 01:07:34 字数 187 浏览 1 评论 0原文

我正在使用 StreamTokenizer 来解析文本,我需要确保 某些标记之间有空格。例如,“5+5”是非法的,但“5 + 5”是有效的。

我真的不太了解 StreamTokenizer;我阅读了 API,但找不到任何可以帮助我的东西。我该怎么做?

I am working with StreamTokenizer to parse text, and I need to make sure that
there's whitespace between certain tokens. For example, "5+5" is illegal, but "5 + 5" is valid.

I really don't know StreamTokenizer that well; I read the API but couldn't find anything to help me. How can I do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

治碍 2024-11-04 01:07:34

您必须将空格设置为“普通字符”。这意味着它们将作为代币单独返回,但不会折叠到其他代币中。示例:

StreamTokenizer st = new StreamTokenizer(new StringReader("5 + 5"));
st.ordinaryChar(32);
int tt = st.nextToken();  // tt = TT_NUMBER, st.nval = 5
tt = st.nextToken();      // tt = 32 (' ')
tt = st.nextToken();      // tt = 43 ('+')
tt = st.nextToken();      // tt = 32 (' ')
tt = st.nextToken();      // tt = TT_NUMBER, st.nval = 5
tt = st.nextToken();      // tt = TT_EOF

不幸的是,您必须在解析器中处理空白标记。我建议滚动你自己的标记器。除非您正在做一些快速而肮脏的事情,否则 StreamTokenizer 几乎总是错误的选择。

You'll have to set spaces as "ordinary characters". This means that they'll be returned as tokens on their own, but not folded into other tokens. Example:

StreamTokenizer st = new StreamTokenizer(new StringReader("5 + 5"));
st.ordinaryChar(32);
int tt = st.nextToken();  // tt = TT_NUMBER, st.nval = 5
tt = st.nextToken();      // tt = 32 (' ')
tt = st.nextToken();      // tt = 43 ('+')
tt = st.nextToken();      // tt = 32 (' ')
tt = st.nextToken();      // tt = TT_NUMBER, st.nval = 5
tt = st.nextToken();      // tt = TT_EOF

Unfortunately, you'll have to deal with whitespace tokens in your parser. I'd recommend rolling your own tokenizer. Unless you're doing something quick and dirty, StreamTokenizer is almost always the wrong choice.

猥琐帝 2024-11-04 01:07:34

此后考虑使用扫描仪。例如:

String input = "5 + 5";
Scanner scanner = new Scanner(input).useDelimiter(" ");
int num1 = scanner.nextInt();
String op = scanner.next();
int num2 = scanner.nextInt();

这是一个简化的示例,假设输入如 "5+5""5 + 5"。您应该随时检查 scanner.hasNext() ,也许在 where 循环中检查以处理更复杂的输入。

Consider using Scanner instead since. E.g.:

String input = "5 + 5";
Scanner scanner = new Scanner(input).useDelimiter(" ");
int num1 = scanner.nextInt();
String op = scanner.next();
int num2 = scanner.nextInt();

This is a simplified example that assumes an input like "5+5" or "5 + 5". You should be checking scanner.hasNext() as you go, perhaps in a where loop to process more complicated inputs.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文