Text from file

edited October 2016 in Questions about Code

I want to tjek if the first letter in the test.txt file is "t". Why does this not work?:

String lines[] = loadStrings("test.txt");
println(lines[0]);

String letter = lines[0].substring(1, 2);
println(letter);

if(letter == "t"){
  print("first letter is t!");
}else{
  print("first letter is not t!");
}

The console says:

ttt-test
t
first letter is not t!

Answers

  • edited October 2016 Answer ✓

    Do not compare strings for equality with == Use .equals()

    Example:

    if( letter.equals("t") ){
    
  • there's a startsWith method on String that does this...

    if (lines[0].startsWith("t")) {
    ...
    }
    
  • edited October 2016

    Besides substring() + equals(), and startsWith(), given you're only interested in checking out 1 char within a String, you can use its charAt() method too: O:-)

    https://Processing.org/reference/String_charAt_.html
    https://Processing.org/reference/char.html

    String[] lines = { "template", "contemplate" };
    String word;
    boolean isT;
    
    word = lines[0];
    isT = word.charAt(0) == 't';
    println("First letter in", word, isT? "is" : "isn't", "t!");
    
    word = lines[1];
    isT = word.charAt(0) == 't';
    println("First letter in", word, isT? "is" : "isn't", "t!");
    
    exit();
    
Sign In or Register to comment.