将字符串吐入不同类型数组的最简单,最有效的方法是什么?示例:
String[] textArr;
String[] numbersArr;
如果可能的话String[] doubleArr
和String[] dateArray
z
//the string I want to split
String splitMe = "Tinus has 99 issues and has to pay $2200.50 for 26 on 2016/10/10";
分裂之后应该是
String[] textArr = ["Tinus","has","issues","and","to","pay","for","on"];
String[] numbersArr = ["99","26"];
String[] doubleArr = ["2200.50"];
String[] dateArr = ["2016/10/10"];
答案 0 :(得分:4)
我可能会选择按空格分割输入字符串,然后使用模式匹配来检查每个条目以确定它所属的位置:
String splitMe = "Tinus has 99 issues and has to pay $2200.50 for 26 on 2016/10/10";
String[] parts = splitMe.split(" ");
List<String> textList = new ArrayList<>();
List<String> numbersList = new ArrayList<>();
List<String> currencyList = new ArrayList<>();
List<String> dateList = new ArrayList<>();
for (String part : parts) {
if (part.matches("\\d*")) {
numbersList.add(part);
}
else if (part.matches("\\$\\d*\\.\\d*")) {
currencyList.add(part);
}
else if (part.matches("\\d{4}/\\d{2}/\\d{2}")) {
dateList.add(part);
}
else {
textList.add(part);
}
}
我没有尝试从货币中正式提取双倍。我还选择使用列表而不是数组来存储各种术语,因为这样可以更好地扩展。我会留给你填写详细信息。
答案 1 :(得分:0)
您可以尝试这样的事情:
>>> import textwrap
>>> for line in textwrap.wrap(t, width=50):
... print(line)
...
Affil of fifth at fat at all the social ball and
said, with all this little in the mid limited and
will cost a lot, for want of a lot of it is I
never do this or below are the innocent of fat in
the annual own none will bit less often were a
little the earth the oven for the area of some of
them some of the atom in the long will recall the
law, will cost you the ball a little less of
Odessa and coal rule the Vikings in at a loss of
our lady of one of the will of the wall routing
visiting little sign of the limited use of a lot
of wind up with a loss of 14 and uncivil will find
a site to lop off call them into solid, a London,
can we stop go to work as a gay sailor kissing a
lot of that scene of the law that on them in this
case will almost a kind wilkinson's, and that a
settlement, or the fog collared of the unknown,
some would call and all of this was a little, some
of us up a lot of letters, union would quit them
or not will be or will lend money to zoning and
will open the door to that of the novel opens in
it and solidity can cut later with boats can die
to only see not open only to six and 0:50 and
world go back a at the fat of that at that
请注意,使用的正则表达式并不理想,但它们适用于您的情况。我使用数组因为我认为这是一个严格的要求。您也可以使用更好的列表。