【问题标题】:How can i read the strings(individually) in a single input, that are seperated by white space? [closed]如何在单个输入中(单独)读取由空格分隔的字符串? [关闭]
【发布时间】:2022-01-20 01:05:39
【问题描述】:
所以,如果给我一个输入,如下:
Hello how
are you
doing? I'm doing
fine! ***
我该怎么做才能得到输出:
There are 9 strings:
1. Hello
2. how
3. are
4. you
5. doing?
6. I'm
7. doing
8. fine!
9. ***
所以基本上,我想要的是单独读取由空格分隔的字符串!
有什么想法吗?
【问题讨论】:
标签:
arrays
c
string
whitespace
【解决方案1】:
package com.tools;
import java.util.StringTokenizer;
public class StringParser {
public void parse(String str)
{
StringTokenizer st = new StringTokenizer(str,"\n\r ");
String token ="";
int num = 0;
while (st.hasMoreElements())
{
token = st.nextElement().toString();
if (token.trim().length() > 0)
{
System.out.println(++num+". "+token);
}
}
}
public static void main (String a[])
{
StringParser st = new StringParser();
String str = "Hello how \r\n"
+ "are you\r\n"
+ "doing? I'm doing \r\n"
+ "fine! *** ";
st.parse(str);
}
}
【解决方案2】:
正如其他人所提到的,使用string.h 中的strtok。它将允许您选择一个分隔符来查找子字符串,在您的情况下它只是" "。然后,您可以循环并找到所有由空格分隔的子字符串。
#include <stdio.h>
#include <string.h>
int main() {
char words[] = "Hello how are you doing? ***";
char *word = strtok(words, " ");
while (word != NULL) {
printf("%s\n", word);
word = strtok(NULL, " ");
}
return 0;
}
输出:
Hello
how
are
you
doing?
***