我正在尝试拆分包含几个选项的多项式字符串:
1. "-x"
2. "x"
3. "-7","-70","-700" etc . . .
4. "-7","-70","-700" etc . . .
5. "-7x","-70x","-700x" etc . . .
6. "7x","70x","700x" etc . . .
7. "x^2","x^20","x^200" etc . . .
8. "-x^2","-x^20","-x^200" etc . . .
9. "-5x^5","-50x^50","-500x^500" etc . . .
10. "5x^5","50x^50","500x^500" etc . . .
我已成功使用str.split()以单个术语分割多项式,如上所示。但是我想分开系数和指数。我不会在这里发布这个,除了我已经阅读了java正则表达式并且我不理解。
我读完了这个: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
我想使用增强的for循环,因为我想在每个循环中省略字符串:
for (String term : polynomialTerm.split("x") {
// for terms like these -5x, -50x, -500x && 5x, 50x, 500x
// term will be the coefficient
}
for (String term : polynomialTerm.split("x^") {
// for terms like these x^2, x^20, x^200 && -2x^2, -20x^20, -200x^200 && 2x^2, 20x^20, 200x^200
// term could be the coefficient or exponent
}
for (String term : polynomialTerm.split("-x^") {
// for terms like these -x^2, -x^20, -x^200
// term should then be the exponent
}
然后我将使用parseInt()从if和else语句中获取循环中的系数或指数,以确保我获取正确的信息