简体   繁体   English

if(s1.Contains(s2)) 似乎总是正确的

[英]if(s1.Contains(s2)) Seems to always be true

sorry, changed the question slightly.对不起,稍微改变了问题。

essentially i want to know if aString contains String .基本上我想知道aString包含String My issue is when comparing say aS a substring of aString ) "aS".contains("String") shows true.我的问题是当比较aS aString的子字符串时, "aS".contains("String")显示为真。

String a="st", b="string"; I ran System.out.println(a.contains(b));我跑了System.out.println(a.contains(b)); That returned false , as expected.正如预期的那样,返回false I have an understanding of contains, i must be missing something else.我对 contains 有所了解,我一定还缺少其他东西。

So It had seemed that my program was working properly, but I made some adjustments and came back and the whole thing stopped working.所以看起来我的程序运行正常,但我做了一些调整并返回,整个程序停止工作。 I sussed out what are usually the common culprits (brackets, file io, etc.) .我想出了什么是常见的罪魁祸首(brackets, file io, etc.) I found if(string.contains(string)) would continually run, ie: always true.我发现if(string.contains(string))会持续运行,即:始终为真。 not sure why this is happening, probably something I missed in the code.不知道为什么会这样,可能是我在代码中遗漏了一些东西。

This is an example of my output (Just a char by char reading of the file):这是我的输出的一个例子(只是一个按字符读取文件的字符):

I nteger G ;

import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;

public class comp{

    public static void main(String[] args){
        ArrayList<String> lines = new ArrayList<String>();
        ArrayList<String> symbolTable = new ArrayList<String>();
        ArrayList<String> parsedFile = new ArrayList<String>();


         try {
                File file = new File("symbolTable.txt");
                Scanner scanner=new Scanner(file);
                while (scanner.hasNextLine()&&symbolTable.add(scanner.nextLine().replaceAll("\\s+","").toLowerCase()));
                scanner.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }


         try {
                File file = new File("APU_CS400_input.txt");
                Scanner scanner=new Scanner(file);
                while (scanner.hasNextLine()&&lines.add(scanner.nextLine().replaceAll("\\s+","").toLowerCase()));
                scanner.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }


         //runs through line by line of the input file
         for(String line: lines){
             String sBuild = "";
             StringBuilder identifier = new StringBuilder("");

             //moves through the line char by char
             for(int i=0;line.length()>i; i++){
                 sBuild+=line.charAt(i);
                 //moves through the symbol table comparing each symbol to each string 
                 //that is built char by char
                 for(String symbol: symbolTable){
                     //if the char string matches the symbol then any identifiers are saved and 
                     //symbols are saved, the string is then reset to empty
            //This is where i seem to get an issue

        ***if(sBuild.contains(symbol)){***
                        if(symbol.length()<sBuild.length()){
                            identifier.append(sBuild,0,sBuild.length()-symbol.length()); 
                            parsedFile.add(identifier.toString());
                            identifier.delete(0,sBuild.length()-symbol.length());
                        }
                        sBuild="";
                        parsedFile.add(symbol);
                     }

                 }
             }
         }


         for(String symbol:parsedFile){
             System.out.println(symbol);
         }

    }

}

Blockquote 

Think of it this way.这么想吧。

s1.contains(s2)

should return true , if a substring of s1 can be found such that应该返回true ,如果可以找到s1的子字符串使得

s1.substring(i, j).equals(s2)

is true.是真的。

If s2 is an empty string, then i = 0, j = 0 is one such substring, so contains() returns true .如果s2是一个空字符串,那么i = 0, j = 0就是这样的一个子字符串,所以contains()返回true

As it should.正如它应该。

if(String.Contains(""))总是应该为真,只要字符串不为空。

You may have to look at this one a bit mathematically to see why s.contains("") is always true.您可能需要从数学上看一下这个,才能明白为什么s.contains("")总是正确的。 Suppose you think of this this way:假设你这样想:

a.contains(b) is true if there are some values i and j such that a.substring(i,j) is equal to b .如果存在一些值ij使得a.substring(i,j)等于b a.substring(i,j)a.contains(b)为真。

If you think about it a bit, you'll see that this is exactly what contains means when the argument is a nonempty string like "xyz" .如果你稍微思考一下,你会发现当参数是一个像"xyz"这样的非空字符串时,这正是contains意思。 If there is some substring of x that equals "xyz" , then s.contains("xyz") is true.如果x某个substring等于"xyz" ,则s.contains("xyz")为真。 If there is no such substring, then s.contains("xyz") is false.如果没有这样的子字符串,则s.contains("xyz")为假。

So it makes sense that the same logic would apply for an empty string, since it applies everywhere else.因此,同样的逻辑适用于空字符串是有道理的,因为它适用于其他任何地方。 And it's always true that a.substring(0,0) equals "" (if a is not null).并且a.substring(0,0)等于"" (如果a不为空)总是正确的。 That's why a.contains("") should always be true.这就是为什么a.contains("")应该总是正确的。

It may not be intuitively obvious from the English meaning of "contains", but when you're dealing with "edge cases" like this, you sometimes have to think in different terms.从“包含”的英文含义来看,直观上可能并不明显,但是当您处理这样的“边缘情况”时,有时您必须以不同的方式思考。 Often, the Javadoc spells things out so that you can easily figure out what happens in the edge cases, without relying on intuition.通常,Javadoc 会详细说明问题,以便您可以轻松地弄清楚在边缘情况下会发生什么,而无需依赖直觉。 Unfortunately, in this case, they didn't.不幸的是,在这种情况下,他们没有。

essentially i want to know if "aString" contains "String".基本上我想知道“aString”是否包含“String”。

Yes, "aString" as a string-value does contain the string-value of "String"是的, "aString"作为字符串值确实包含"String"的字符串值

My issue is when comparing say "aS" (a substring of "aString") "aS".contains("String") shows true.我的问题是在比较时说“aS”(“aString”的子字符串)“aS”.contains(“String”) 显示为真。

Are you sure?你确定吗? This cannot be , therefore I rather suspect bugs in your code.不可能,因此我宁愿怀疑您的代码中存在错误。


To spare youself of "empty String symbols" consider this:为了避免“空字符串符号”,请考虑:

try {
  File file = new File("symbolTable.txt");
  Scanner scanner=new Scanner(file);
  while (scanner.hasNextLine()) {
    // toLowerCase will do nothing for characters that are not letters
    // Don't spend CPU cycles with regex
    String symbolLine=scanner.nextLine().toLowerCase();
    // Collect the symbol only if non-empty?? This will save you from empty symbols
    if(symbolLine.trim().length()>0) {
      symbolTable.add(symbolLine); // or .add(symbolLine.trim()) ???
    }
  }
  scanner.close();
} catch (Exception ex) {
  ex.printStackTrace();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM