【问题标题】:how to Split a string with in double quotes in java如何在java中用双引号分割字符串
【发布时间】:2013-08-24 23:58:55
【问题描述】:

我对拆分字符串有疑问,我的要求是我必须用'and'或'or'分隔字符串,如果2或3个单词用双引号括起来,我必须保持这个为单个字符串。请看下面的例子,这里我给出了这样的字符串 "India or welcome and \"This is America.\"";

输出应如下所示:

  1. 第一个字符串 --> 印度

  2. 第二个字符串 --> 欢迎

  3. 第三个字符串 ---> 这是美国。

这仅用于示例,我必须从大段落中拆分出这样的字符串..

参考:

public class Test 
{  
    public static void main(String[] args) 
    { 
       try{
           String s2="India or welcome and \"This is America.\"";
           System.out.println(s2);
       }
       catch(Exception e)
       {
           System.err.println("Exception Ocurred:"+e);
       }
    } 
}

请给我有关此要求的建议,并建议我拆分字符串的有效方法。哪个是最好的 stringtokenizer 或 String.split()。

另一件事是我的字符串也可能这样 String s2="一二三四\"五六七\"" 我必须像下面这样拆分它,

  1. 一个
  2. 两个
  3. 三个
  4. 四个
  5. 五六七

我也想要这样..请给我建议

提前致谢。

【问题讨论】:

  • 你的例子对我来说没有意义。 “This is America”无论如何都不会被拆分,因为它既不包含“and”,也不包含“or”。双引号根本不影响这一点。
  • 我同意。要求是矛盾的。该问题无法以当前形式回答。

标签: java string


【解决方案1】:

这是你需要的吗?

public static void main(String[] args) {
    try {
        String s2 = "India or welcome and \"This is America.\"";
        String[] split = s2.split("and|or");
        System.out.println(s2);
        for (String string : split) {
            System.out.println(string.trim());
        }
    } catch (Exception e) {
        System.err.println("Exception Ocurred:" + e);
    }
}

如果引号中有“和”或“或”,我正在徘徊你需要什么。示例:

String s2 = "India or welcome and \"This and America.\"";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-26
    • 2011-08-09
    • 2013-04-02
    • 1970-01-01
    • 1970-01-01
    • 2018-02-07
    • 1970-01-01
    • 2016-01-17
    相关资源
    最近更新 更多