【发布时间】:2019-05-21 10:01:51
【问题描述】:
我一直在努力弄清楚如何从我正在从文件中读取的长度未知的字符串中获取一个长度未知的单词。字符串中我想要的单词总是用“。”分隔。和/或“&”,整个字符串被引号包围。例如:“.Word.Characters&Numeric&Letters.Typos&Mistypes。”我知道每个“。”的位置。和“&”以及它们出现的次数。
我想根据单词是否用“。”分隔,将单词输入数组 Example[i][j]。或“&”。所以“。”之间包含的单词。将被设置到数组的第 i 列,由“&”链接的单词到数组的 j 行。
输入字符串可以包含大量可变数量的单词。这意味着可能只有一个感兴趣的词,或者一百多个。
我更喜欢使用数组来解决这个问题。从我读过的内容来看,正则表达式会很慢,但是可以。 split() 也可能有效,但我想我必须事先知道要查找哪些词。
从此字符串:“.Word.Characters&Numeric&Letters.Typos&Mistypes。”我希望得到:(不用担心是行还是列)
[[字],[null],[null]],
[[字符],[数字],[字母]],
[[Typos],[Mistypes],[null]]
从此字符串“.Alpha.Beta.Zeta&Iota”。我希望得到:
[[Alpha],[null]],
[[Beta],[null]],
[[Zeta],[Iota]]
//NumerOfPeriods tells me how many word "sections" are in the string
//Stor[] is an array that holds the string index locations of "."
for(int i=0;i<NumberOfPeriods;i++)
{
int length = Stor[i];
while(Line.charAt(length) != '"')
{
length++;
}
Example[i] = Line.substring(Stor[i], length);
}
//This code can get the words separated by "." but not by "&"
//Stor[] is an array that holds all string index locations of '.'
//AmpStor[] is an array that holds all string index locations of '&'
int TotalLength = Stor[0];
int InnerLength = 0;
int OuterLength = 0;
while(Line.charAt(TotalLength) != '"')
{
while(Line.charAt(OuterLength)!='.')
{
while(Line.charAt(InnerLength)!='&')
{
InnerLength++;
}
if(Stor[i] > AmpStor[i])
{
Example[i][j] = Line.substring(Stor[i], InnerLength);
}
if(Stor[i] < AmpStor[i])
{
Example[i][j] = Line.substring(AmpStor[i],InnerLength);
}
OuterLength++;
}
}
//Here I run into the issue of indexing into different parts of the array i & j
【问题讨论】:
-
我首先考虑的不是尝试一步完成,而是可能通过多个步骤分解问题,每个步骤都在最后一步的结果范围内工作。另一个考虑因素可能是考虑使用一个或多个正则表达式
-
欢迎来到 Stack Overflow!寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定问题或错误和重现它所需的最短代码在问题本身。没有明确问题陈述的问题对其他读者没有用处。请参阅:How to create a Minimal, Complete, and Verifiable example。
-
你上面的所有代码都可以放入:String test2 = ".Alpha.Beta.Zeta&Iota."; for (String s : test2.split("\\p{P}")) { System.out.println(s); } 考虑如何构建代码,因为它对于没有副作用的进一步开发至关重要。
-
这是作业题吗?
标签: java arrays string indexing substring