首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Java中将字符串拆分成多个部分的安全方法是什么?

在Java中将字符串拆分成多个部分的安全方法是什么?
EN

Stack Overflow用户
提问于 2013-04-03 03:57:13
回答 3查看 2.3K关注 0票数 0

让我澄清我所问的问题。我正在编写一个java程序,它通过一个名为JLine2的读行库从键盘上获取输入。库将整个行类型作为命令,而不是将其拆分为分隔的命令和参数。我正在寻找的是一种安全的方法来拆分作为输入传递的字符串。

我尝试过使用数组,但是由于我处于概念的早期阶段,我还不知道我最大的命令会有多少参数,所以使用一个预初始化的数组,我不认为会起作用。我遇到的问题是,当我检查数组中的空值时,或者当我检查是否存在特定的命令或参数时。Java总是抛出一个关于数组索引超出作用域或什么的异常。因为数组实际上没有数组索引1的值,而数组索引1是数组索引0中命令的参数。

因此,我要寻找的是一种方法,可以将字符串安全地分割成几个部分,而不需要Java在出现和数组异常时对我大喊大叫。

这是我能提供的非常小的代码..。

ConfigShell.class

代码语言:javascript
复制
package shell; 

import java.io.IOException;

import configFS.ConfigFS;
import jline.console.ConsoleReader;

public class ConfigShell {

    private ConfigFS config;

    public ConfigShell() throws IOException {

        config = new ConfigFS();

    }

    public void init() throws IOException {

        ConsoleReader console = new ConsoleReader();

        // When the program starts we want to be placed at / (root).
        console.setPrompt(">> ");

        // In this case an infinite loop is better than a loop based on whether line is equal to null.
        // This allows line to be equal to null and still stay inside the shell.
        while (true) {

            String line = console.readLine();

            if (line != null) {

                // If pre-initialize the array I can check for null as a value for an array index.
                // If I did this at time I needed the array and there were not enough index occupied the system would return an exception.
                String[] cmdArgs = new String[4];

                // We need to split up the incoming line because JLine2 does not do it for me.
                // This allows me to evaluate the entire command piece by piece rather all at once.
                cmdArgs = line.split("\\s+");

                if (cmdArgs[0] != null && cmdArgs[0].equals("add")) {

                    if (cmdArgs[1] != null && cmdArgs[1].equals("server")) {

                        if (cmdArgs[2] != null) {

                            config.addServer(cmdArgs[2]);
                            System.out.println("Added server " + cmdArgs[2] + " to the configuration successfully.");

                        }

                    }

                }

                if (cmdArgs[0].equals("exit")) {

                    System.exit(0);

                }

            }

        }

    }

}

用于测试的注释:我的Start.class主方法在上面的文件中调用init方法.

EN

回答 3

Stack Overflow用户

发布于 2013-04-03 04:18:04

你可以:

代码语言:javascript
复制
        String cmdArgs = line.split("\\s+");

然后,在访问任何特定索引之前,检查数组的大小,以免获得ArrayIndexOutOfBoundException。

就像这样:

代码语言:javascript
复制
if(cmdArgs.length>=2){
//It means you have at least 2 elements
//Now its safe to access cmdArgs[0] and cmdArgs[1]
}
票数 1
EN

Stack Overflow用户

发布于 2013-04-03 04:22:01

如果您的所有问题都是要为可变数目的字符串拥有一个存储空间,那么您可以使用ArrayList<String>对象。

你把它声明成ArrayList<String> as = new ArrayList<String>();

然后,当您从命令字符串中拆分某些内容时,只需使用add方法:as.add(yourString);

如果需要检索ArrayList的特定元素,可以使用其get方法:as.get(0);

您可以使用for each循环处理所有元素:

代码语言:javascript
复制
for(String str: as) {
println(str):
}

看看这里的信息一个例子

票数 0
EN

Stack Overflow用户

发布于 2013-04-03 04:28:20

因为我认为您可以使用StringTokenizer类及其方法来满足您的需求。

参见下面的示例代码:

代码语言:javascript
复制
 if(line!=null)
    {
     StringTokenizer st=new StringTokenizer(line);// by default it takes space as delimiter....you can use as required as second argument in constructor...
     while(st.hasMoreTokens())
     {
      String token1=st.nextToken();
     // do your stuffs here..........
     // I don't know exactly about your required logic here......

   /* if(token1.equals("add"))
      {
         String token2=st.nextToken();
         if(token2.equals("server"))
         {
           String token3=st.nextToken();
             config.addServer(token3);
             System.out.println("Added server " + token3 + " to the configuration successfully.");
         }
       }
     */
    }// while closing...
   }// outer if closing...

或者正如PM 77-1告诉你可以使用ArrayList。但正如我的观点,LinkedList应该是一个更好的选择。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15778587

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档