We are given a string, we need check whether the first and last characters of the string str are equal or not. Case sensitivity is to be considered. Examples :
Input : university
Output : Not Equal
Explanation: In the string "university", the first character is 'u'
and the last character is 'y', as they are not equal, "Not Equal" is the output.
Input : racecar
Output : Equal
Explanation: In the string "racecar", the first character is 'r'
and the last character is 'r', as they are equal, "Equal" is the output.
// Java program to check if the first and the last
// characters of a string are equal or not.
classGFG {
publicstaticintareCornerEqual(String s)
{
intn = s.length();
if(n < 2)
return-1;
if(s.charAt(0) == s.charAt(n-1))
return1;
else
return0;
}
// Driver code
publicstaticvoidmain(String[] args)
{
String s = "GfG";
intres = areCornerEqual(s);
if(res == -1)
System.out.println("Invalid Input");
elseif(res == 1)
System.out.println("Equal");
else
System.out.println("Not Equal");
}
}
Python3
# Python program to check
# if the first and the
# last characters of a
# string are equal or not.
st ="GfG"
if(st[0] ==st[-1]):
# print output
# if condition
# is satisfied
print("Equal")
else:
# print output
# if condition is
# not satisfied
print("Not Equal")
# This code is contributed by
# shivi Aggarwal
C#
// Java program to check if the first and the last
// characters of a string are equal or not.
usingSystem;
classGFG
{
publicstaticintareCornerEqual(String s)
{
intn = s.Length;
if(n < 2)
return-1;
if(s[0] == s[n - 1])
return1;
else
return0;
}
// Driver code
staticpublicvoidMain ()
{
String s = "GfG";
intres = areCornerEqual(s);
if(res == -1)
Console.WriteLine("Invalid Input");
elseif(res == 1)
Console.WriteLine("Equal");
else
Console.WriteLine("Not Equal");
}
}
// This code is contributed by Ajit.
.
PHP
<?php
// PHP program to check if
// the first and the last
// characters of a $are
// equal or not.
functionareCornerEqual($s)
{
$n= strlen($s);
if($n< 2)
return-1;
if($s[0] == $s[$n- 1])
return1;
else
return0;
}
// Driver code
$s= "GfG";
$res= areCornerEqual($s);
if($res== -1)
echo("Invalid Input");
elseif($res== 1)
echo("Equal");
else
echo("Not Equal");
// This code is contributed by
// Manish Shaw(manishshaw1)
?>
Output:
Equal
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy