【问题标题】:Issue while comparing a long string with a string of array将长字符串与数组字符串进行比较时出现问题
【发布时间】:2014-05-30 06:29:44
【问题描述】:

主要思想:我有一个 URL(字符串),还有一个包含少量数据(字符串)的数组。我想使用contains() 方法检查是否在 URL 中找到了 Array 中的字符串。

我的代码结构:首先将字符串单词存储在一个文本文件中。我将读取该文件并将值存储在JTextArea 中。从JTextArea 我使用getText() 方法并将值存储在一个数组中。现在,我将使用contains 方法检查字符串。这是我的代码:

这个函数(工作正常)读取文本文件并写入JTextArea

JTextArea jta = new JTextArea(300,300);
Reader reader = null;
try {
    reader = new FileReader(new File("res/pass.txt"));
    jta.read(reader, "The force is strong with this one");
} catch (Exception exp) {
    exp.printStackTrace();
} finally {
    try {
        reader.close();
    } catch (Exception exp) {}
}

在此之前等等,这些是之前存储在pass.txt 中的单词。举个例子:

red~
绿色~
黄色~
黑色~

这个函数(工作正常)知道数组的长度。

String getArr="";
int getCount=0, z=0, lens = jta.getText().length();
for(int i=0; i<lens; i++){
    if(jta.getText().charAt(i)=='~'){
        getCount++;
    }
}

这个函数(工作正常)将字符串存储在数组中。

String[] arr = new String[getCount];
for(int i=0; i<lens; i++){
    if(jta.getText().charAt(i)!='~'){
        getArr = getArr+jta.getText().charAt(i);
    }
    else{
        arr[z] = getArr; getArr=""; z++;
    }
}

问题从这里开始。我试图在控制台中打印所有 Array 值,它正在显示所有值。但是,当我进行比较时,它并没有像我预期的那样工作。

String txtGetURL = txtURL.getText(); //The URL
Boolean ok=true;

for(int i=0; i<arr.length; i++){
    System.out.print(arr[i]);
}
for(int i=0; i<arr.length; i++){
    if(txtGetURL.toLowerCase().contains(arr[i].toLowerCase())){
       ok=false;
    }
}

if(ok==false){
    JOptionPane.showMessageDialog(null, "URL Blocked!"); 
}
else{
   JOptionPane.showMessageDialog(null, "Whitelist URL"); 
}

假设我在文本字段中输入的示例 URL 是 http://www.example.com/ex/examplered.html,而不是显示 URL Blocked,而是显示 Whitelist URL。请帮我解决我的问题。提前致谢。

【问题讨论】:

    标签: java arrays string contains


    【解决方案1】:

    你可以用这个,

    org.apache.commons.lang3.StringUtils.containsIgnoreCase(txtGetURL , arr[i].trim());
    

    通过使用它,您可以忽略大小写并检查它是否包含以及

    如果你确定字符串只包含字母,你可以通过

    String resultString = arr[i].replaceAll("[^\\p{L}\\p{Nd}]+", "");
    

    【讨论】:

    • 但是我应该说,在你举例子的时候要小心。当然,您可以在将其放到此站点之前对其进行更改。它可能不会影响问题或代码。
    • 谢谢。我从你的回答中学到了一些新技术。
    【解决方案2】:

    在处理String对象时,无需手动构建基于字符和索引的解析,有很多方法可以提供帮助。

    在这里,您可能想要使用split()trim()

    最初您的值为red~,然后将它们放入文本区域,这可能会为其添加一些空白。所以你最终处理的值可能是: red ~ \n 或一些变体。

    因此,首先在~ 字符上使用split(),然后在结果拆分数组的第一个元素上使用trim()

    在这里,我编写了一个快速测试类来展示这一点:

    public class BlockedWords {
    
        public static void main(final String[] args) {
            //Various different types of white space within the input.
            final String[] input = {" A ~\n\r","\n\rB ~","\nE\r~"," G\n~"};
    
            final String[] urls = {"www.url.com/A","www.url.com/B","www.url.com/C","www.url.com/D",
                    "www.url.com/E","www.url.com/F","www.url.com/G","www.url.com/H"};
    
            final BlockedWords whiteListing = new BlockedWords(input);
    
            for (final String url : urls) {
                if( whiteListing.containsBlockedWord(url) ) {
                    System.out.println(url + " is blocked.");
                    continue;
                }
                System.out.println(url + " is whitelisted.");
            }
        }
    
    
        private String[] blockedWords;
    
        public BlockedWords(final String[] blockedWords) {
            for (int i = 0; i < blockedWords.length; i++) {
                //Split on the ~ character to get an array of {"word", ""} then just take the word. in index 0.
                //Then trim it in case there are any whitespace characters still around the word.
                blockedWords[i] = blockedWords[i].split("~")[0].trim();
            }
    
            this.blockedWords = blockedWords;
        }
    
        public boolean containsBlockedWord(final String url) {
            for (final String blockedWord : this.blockedWords) {
                if( url.toLowerCase().contains( blockedWord.toLowerCase() ) ) {
                    return true;
                }
            }
            return false;
        }
    }
    

    输出是这样的:

    www.url.com/A 被屏蔽。

    www.url.com/B 被屏蔽。

    www.url.com/C 被列入白名单。

    www.url.com/D 被列入白名单。

    www.url.com/E 被屏蔽。

    www.url.com/F 被列入白名单。

    www.url.com/G 被屏蔽。

    www.url.com/H 被列入白名单。

    【讨论】:

      【解决方案3】:

      我猜问题是您的数组中的字符串包含行分隔符 (\n) 在这种情况下,由于 url 不包含它,contains 方法返回 false。

      要解决这个问题,修改你的代码(我也建议使用String.split(),它更简单):

      String[] arr = jta.getText().split("~");
      

      当你检查时,使用trim() 来避免行分隔符:

      if (txtGetURL.toLowerCase().contains(arr[i].trim().toLowerCase())) {
        ok = false;
      }
      

      【讨论】:

      • 感谢您的回答。我只是像这样更改了这条线,现在它工作正常。 arr[z] = getArr.trim(); getArr=""; z++;
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-04
      相关资源
      最近更新 更多