In: Computer Science
/**
* Returns the string formed by alternating the case of
the characters in
* the specified string. The first character in the
returned string is in
* lowercase, the second character is in uppercase, the
third character is
* in lowercase, the fourth character is in uppercase,
and so on.
* Examples:
*
* <ul>
*
<li><code>alternatingCaps("a")</code> returns
<code>"a"</code>
*
<li><code>alternatingCaps("ab")</code> returns
<code>"aB"</code>
*
<li><code>alternatingCaps("abc")</code> returns
<code>"aBc"</code>
*
<li><code>alternatingCaps("XYZ")</code> returns
<code>"xYz"</code>
*
<li><code>alternatingCaps("Toronto")</code>
returns <code>"tOrOnTo"</code>
*
<li><code>alternatingCaps("eecs2030")</code>
returns <code>"eEcS2030"</code>
* </ul>
*
* <p>
* The conversion of characters to lower or uppercase
is identical to
* that performed by the methods
<code>Character.toLowerCase(int)</code>
* and
<code>Character.toLowerCase(int)</code>
*
* @param s
*
a string
* @return the string formed by alternating the case of
the characters in s
*/
public static String alternatingCaps(String s) {
return "";
}
public class AlternatingCaps { /** * Returns the string formed by alternating the case of the characters in * the specified string. The first character in the returned string is in * lowercase, the second character is in uppercase, the third character is * in lowercase, the fourth character is in uppercase, and so on. * Examples: * * <ul> * <li><code>alternatingCaps("a")</code> returns <code>"a"</code> * <li><code>alternatingCaps("ab")</code> returns <code>"aB"</code> * <li><code>alternatingCaps("abc")</code> returns <code>"aBc"</code> * <li><code>alternatingCaps("XYZ")</code> returns <code>"xYz"</code> * <li><code>alternatingCaps("Toronto")</code> returns <code>"tOrOnTo"</code> * <li><code>alternatingCaps("eecs2030")</code> returns <code>"eEcS2030"</code> * </ul> * * <p> * The conversion of characters to lower or uppercase is identical to * that performed by the methods <code>Character.toLowerCase(int)</code> * and <code>Character.toLowerCase(int)</code> * * @param s a string * @return the string formed by alternating the case of the characters in s */ public static String alternatingCaps(String s) { String result = ""; for (int i = 0; i < s.length(); i++) { if (i % 2 == 0) { result += Character.toLowerCase(s.charAt(i)); } else { result += Character.toUpperCase(s.charAt(i)); } } return result; } public static void main(String[] args) { System.out.println(alternatingCaps("a")); System.out.println(alternatingCaps("ab")); System.out.println(alternatingCaps("abc")); System.out.println(alternatingCaps("XYZ")); System.out.println(alternatingCaps("Toronto")); System.out.println(alternatingCaps("eecs2030")); } }