Using substring. What am I doing wrong?

println(p.state.substring(0,1), p.state);
if (p.state.substring(0,1) == "W") {
  println("this is a test");
}

p.state is “WPawn”
p.state.substring(0, 1) is “W”

However, “this is a test” is not being printed and I have no clue why.
All I want to do is get the first character of the p.state string and see if it is “W” or not.

I have also tried the character W but it doesn’t work either

String myString = "Lollipops and Candyfloss";
println(myString.substring(0,1), myString);
if (myString.substring(0,1).equals("L")) {
  println("this is a test");
}

reference vs value testing

you could also do

if (myString.substring(0,1).charAt(0) == 'L') {
  println("this is a test");
}

but i don’t know why you would. instead it would be better to skip the substring altogether if you are just testing a single character and use charAt instead or basically this instead of the first code in this post

String myString = "Lollipops and Candyfloss";
if (myString.charAt(0) == 'L') {
  println("this is a test");
}
2 Likes

Hello,

Some Processing references:

:)