Home > Mobile >  AP Computer Science String Methods
AP Computer Science String Methods

Time:12-06

Write the method body for ​compareStarts​, which takes two String parameters, ​s1​ and ​s2​, and returns ​true​ if they start with the same character, and ​false​ otherwise.

I'm just confused...

I know I need to use "if" and either string.equals() method or == method.

CodePudding user response:

public static boolean compareStarts(String s1, String s2) {
  // Check if the strings are empty
  if (s1.length() == 0 || s2.length() == 0) {
    return false;
  }

  // Get the first character of each string
  char c1 = s1.charAt(0);
  char c2 = s2.charAt(0);

  // Compare the first characters of the strings
  return c1 == c2;
}

The compareStarts method takes two strings as parameters, s1 and s2. It checks if either of the strings are empty, and returns false in that case because empty strings don't have a first character. If the strings are not empty, it gets the first character of each string using the charAt method, and then compares them using the == operator. If the characters are the same, the method returns true, otherwise it returns false.

CodePudding user response:

In javascript, it checks if the first string s1 initial letter is equal to the s2 initial letter and returns an boolean(true if it's equal, false if it's not equal), here's the code:

const checkStrings = (s1,s2) =>{
   return s1.startsWith(s2.charAt(0));

}

checkStrings('fest', 'test'); // false
checkStrings('test', 'test'); // true
  • Related