A C
A C

Reputation: 427

Java substring in a string

I know this has question has been asked countless times.. but I can't seem to get it to work. the problems are,

  1. Even converting everything to lower case doesn't work out when "computer" and "Comp" are entered.
  2. If the string is a sentence (I add a space), it essentially skips the substring code and says "Not in the string"..

Help is appreciated. thanks!

Scanner in=new Scanner(System.in);
System.out.println("\fEnter the main string:");

String GivenString=in.next();
System.out.println("Enter the substring :");

String SubString=in.next();

GivenString.toLowerCase();
SubString.toLowerCase();

if(GivenString.indexOf(SubString)!=-1)
{
    System.out.println("Substring is in the given string.");
}
else
{
    System.out.println("Substring is not in the given string.");
}

Upvotes: 0

Views: 604

Answers (1)

Mike Tunnicliffe
Mike Tunnicliffe

Reputation: 10762

Strings are immutable and toLowerCase() returns a new String object. These lines:

GivenString.toLowerCase();
SubString.toLowerCase();

...do not modify the values in GivenString and SubString.

You would need to modify them to:

GivenString = GivenString.toLowerCase();
SubString = SubString.toLowerCase();

Upvotes: 7

Related Questions