java 如何拆分字符串并将其存储在数组中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16078686/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 21:50:23  来源:igfitidea点击:

how to split the string and store it in array

javaarraysstring

提问by Jivan

I have tried the following example but it gives following out put output[]. I have pass the string "1.0" to function calculatePayout()and want to store the 1 in s[0]and 0 in s[1]

我已经尝试了以下示例,但它给出了以下输出 output[]。我已将字符串“1.0”传递给函数,calculatePayout()并希望将 1s[0]和 0存储在s[1]

import java.util.Arrays;


    public class aps {

        public void calculatePayout(String amount)
        {
            String[] s = amount.split(".");
            System.out.println("output"+Arrays.toString(s));
        }

    public static void main(String args[])
    {
        new aps().calculatePayout("1.0");
    }
    }

回答by AlexR

Method split()accepts regular expression. Character .in regular expressions means "everything". To split your string with .you have to escape it, i.e. split("\\."). The second back slash is needed because the first one escapes dot for regular expression, the second escapes back slash for java compiler.

方法split()接受正则表达式。.正则表达式中的字符意味着“一切”。要拆分字符串,.您必须将其转义,即split("\\."). 需要第二个反斜杠,因为第一个转义正则表达式的点,第二个转义 java 编译器的反斜杠。

回答by BobTheBuilder

Try escaping the dot:

尝试转义点:

String[] s = amount.split("\.");

As dot is "Any character" in regex.

因为点是正则表达式中的“任何字符” 。

回答by Averroes

Try amount.split("\\.")

尝试 amount.split("\\.")

Splitmethod uses a regex so you need to use the correct syntax and escape the dot.

拆分方法使用正则表达式,因此您需要使用正确的语法并转义点。

回答by PermGenError

.is a metacharcteror special character in regex world. String#split(regex)expects regex as parameter, you either have to escape it with backslash or use character class in-order to treat it as a normal character

.是正则表达式世界中的元字符或特殊字符。String#split(regex)期望正则表达式作为参数,您必须使用反斜杠对其进行转义或使用字符类才能将其视为普通字符

Either amount.split("\\.");or amount.split("[.]");

无论是amount.split("\\.");amount.split("[.]");

回答by Drogba

Try

尝试

amount.split("\.")

split method accepts a regular expression

split 方法接受一个正则表达式