Here is the code that we wrote in class today.
public static boolean beginsAndEnds(String str) {
//returns whether str begins and ends with the same char
//this is 5th period code; 6th period did first version below
/*
if(str.charAt(0) == str.charAt(str.length()-1)) {
return true;
}
return false;
*/
//return (str.charAt(0) == str.charAt(str.length()-1));
return str.substring(0,1).equals(str.substring(str.length()-1));
}
public static String firstWord(String str) {
//return the first word (before first space) in str
/*
//5th period:
String first = "";
for(int i=0; str.charAt(i) != ' '; i++) {
first = first + str.charAt(i);
}
return first;
*/
//6th period (using arrays, which we haven't covered yet):
/*
String[] strs = str.split(" ");
String word = strs[0];
return word;
*/
//both classes:
//find index of the first space
int i = 0;
//for(i=0; str.charAt(i) != ' '; i++);
while(i < str.length() && str.charAt(i) != ' ') {
i++;
}
return str.substring(0,i); //return the first word
}
public static int numFirst(String str) {
char first = str.charAt(0); //first character
int count = 1;
for(int i=1; i < str.length(); i++) {
if(str.charAt(i) == first) {
count++;
}
}
return count;
}
//5th period:
public static int numMost(String str) {
//return number of occurences of most common char
int most = 0; //number of occurrences for most common so far
//count 0th character
char first = str.charAt(0); //first character
int count = 1;
for(int i=1; i < str.length(); i++) {
if(str.charAt(i) == first) {
count++;
}
}
most = count;
for(int j=1; j < str.length(); j++) {
//count jth character and see if it's more common
char jth = str.charAt(j); //jth character
count = 0;
for(int i=0; i < str.length(); i++) {
if(str.charAt(i) == jth) {
count++;
}
}
if(count > most) {
most = count; //jth char is new most common
}
}
return most;
}
//6th period:
public static int countN(String str, int n){
// Count the character at index N, assuming N is less than str.length()
int count = 0;
char i = str.charAt(n);
for(int j = 0; j < str.length(); j++){
if(str.charAt(j) == i){
count++;
}
}
return count;
}
//6th period (using function above):
public static int getMaxCountChar(String str){
// Calculate the number of charcter that appears most
int i = 0;
int maxCount = 0;
while ( i < str.length()){
int count = countN(str, i);
if (count > maxCount){
maxCount = count;
}
i++;
}
return maxCount;
}
//6th period: (actually finding the most common character)
public static char getMaxCharLast(String str){
// Calculate the charcter that appears most (last one)
int i = 0;
char letter = ' ';
int maxCount = 0;
while ( i < str.length()){
int count = countN(str, i);
if (count >= maxCount){
maxCount = count;
letter = str.charAt(i);
}
i++;
}
return letter;
}
}