• Strings & Palindromes in Javascript
    • Strings
      • Example 1: Finding the Length of a String using length() in Java.
      • Example 2: Concatenating Strings using + in Java
    • Popcorn #4 Hack
      • Java Code:

Strings & Palindromes in Javascript

Strings

JavaScript has roots from Java. The 1st two examples we will show similarities

A string is an ordered sequence of characters. In programming, a string can contain letters, numbers, spaces, and even special characters. Strings are used to represent text in many programming languages.

Strings can also have procedures and methods that perform operations like finding their length, combining multiple strings (concatenation), or extracting parts of them (substrings).

Example 1: Finding the Length of a String using length() in Java.

In Java, we can use the length() method to find out how many characters a string contains. This includes letters, spaces, and numbers.


String str = "APCSP";
// Finding the length of the string
int length = str.length();
    
// Output the result
System.out.println("The length of the string \"APCSP\" is: " + length);
%%js

// JavaScript String length code cell
// Instead of String in Java we use var or let in JavaScript, in this case we use var
var str = "APCSP";
var length = str.length;
// Ouptut in JavaScript is done using console.log, you must use the console to see the output
console.log("String length of", str, "is:", length);

Example 2: Concatenating Strings using + in Java

The + operator is used to combine two strings into one.

In this example, part1 + part2 combines the strings "AP" and "CSP" into one string, resulting in "APCSP".


String part1 = "AP";
String part2 = "CSP";

// Concatenating the two strings
String result = part1 + part2;

// Output the result
System.out.println("The concatenated string is: " + result);
%%js

// JavaScript String concatenation code cell
// This time we use let instead of var 
let str1 = "AP";
let str2 = "CSP";
// The two strings are concatenated using the + operator
let result = str1 + str2;
console.log("Concatenation of:", str1, " + ", str2, " = ", result);

Popcorn #4 Hack

This hack will help you practice string manipulation in Java. You will:

  • Find the number of characters in your last name using length().
  • Concatenate your first and last name together using the + operator.
  • Use the substring() method to extract characters from the 3rd to the 6th position of your concatenated name.

Java Code:

public class PopcornHack4 {
public static void main(String[] args) {
    // Find the number of characters in your last name
    String lastName = "Bharadwaj";
    int length = lastName.length();
    System.out.println("The number of characters in your last name is: " + length);

    // Concatenate your first and last names together
    String firstName = "Aditi";
    String fullName = firstName + lastName;
    System.out.println("Your full name is: " + fullName);

    // Use substring to show only the 3rd to 6th characters (index 2 to 6)
    String substring = fullName.substring(2, 6);
    System.out.println("Substring (3rd to 6th characters): " + substring);
}
}

In this example, length() is used to find the number of characters in the last name, + is used to concatenate the first and last names, and substring() extracts the 3rd to 6th characters of the concatenated string.

    <!-- Heading -->
    <h2>Palindromes</h2>

    <!-- Body Text -->
    <p>A <strong>palindrome</strong> is a sequence of characters that reads the same forward as it does backward. This applies to strings, numbers, or phrases. When working with palindromes in coding, we typically ignore spaces, punctuation, and case sensitivity.</p>

    <p>For example, the following are palindromes:</p>
    <ul>
        <li><code>madam</code></li>
        <li><code>racecar</code></li>
        <li><code>121</code></li>
        <li><code>A man a plan a canal Panama</code> (ignoring spaces and capitalization)</li>
    </ul>

    <p>In programming, we can write a function that checks if a string is a palindrome by:</p>
    <ol>
        <li>Removing any spaces and punctuation from the string.</li>
        <li>Converting all characters to lowercase.</li>
        <li>Comparing the string to its reversed version.</li>
    </ol>

    <!-- Example Code -->
    <p>Heres an example of how this can be done in Java:</p>

    <pre><code>public class PalindromeChecker {
    
    // Function to check if a string is a palindrome
    public static boolean isPalindrome(String str) {
        // Step 1: Remove non-alphanumeric characters and convert to lowercase
        String cleanedStr = str.replaceAll("[^A-Za-z0-9]", "").toLowerCase();

        // Step 2: Reverse the cleaned string
        String reversedStr = new StringBuilder(cleanedStr).reverse().toString();

        // Step 3: Compare the cleaned string with its reverse
        return cleanedStr.equals(reversedStr);
    }

    public static void main(String[] args) {
        // Test cases
        System.out.println(isPalindrome("A man a plan a canal Panama"));  // Output: true
        System.out.println(isPalindrome("hello"));  // Output: false
    }
}
</code></pre>

    <p>This Java function works by cleaning the input string, reversing it, and then comparing it to the original cleaned version to check if it's a palindrome.</p>


    <!-- Heading -->
    <h1>Text Analyzer Hack</h1>

    <!-- Body Text Explanation -->
    <p>This hack creates a <strong>text analyzer</strong> that processes a string input and provides useful information about it. Specifically, the program will:</p>
    
    <ul>
        <li>Count the total number of characters in the string, including spaces and numbers.</li>
        <li>Count the number of vowels (a, e, i, o, u) in the string.</li>
        <li>Calculate the average length of the words in the string.</li>
        <li>Ensure that the program handles both uppercase and lowercase characters.</li>
    </ul>

    <p>The text analyzer is useful for understanding the basic structure of any input string and can easily be extended to add more features, like finding palindromes in the input.</p>

    <!-- Java Code for Text Analyzer -->
    <p>Heres the Java code for the text analyzer:</p>

    <pre><code>import java.util.Scanner;

public class TextAnalyzer {

    // Method to count the vowels in a string
    public static int countVowels(String str) {
        int vowelCount = 0;
        str = str.toLowerCase();
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
                vowelCount++;
            }
        }
        return vowelCount;
    }

    // Method to calculate the average word length
    public static double averageWordLength(String str) {
        String[] words = str.split("\\s+");
        int totalLength = 0;
        for (String word : words) {
            totalLength += word.length();
        }
        return (double) totalLength / words.length;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // Step 1: Accept user input
        System.out.println("Enter a string: ");
        String input = scanner.nextLine();
        
        // Step 2: Count total characters (including spaces and numbers)
        int totalCharacters = input.length();

        // Step 3: Count total vowels
        int totalVowels = countVowels(input);

        // Step 4: Calculate average word length
        double avgWordLength = averageWordLength(input);

        // Output the results
        System.out.println("Total Characters (including spaces): " + totalCharacters);
        System.out.println("Total Vowels: " + totalVowels);
        System.out.println("Average Word Length: " + String.format("%.2f", avgWordLength));

        scanner.close();
    }
}
</code></pre>

    <p>Heres how the program works:</p>
    <ul>
        <li>The program accepts input from the user.</li>
        <li>It then counts the total number of characters in the input string, including spaces.</li>
        <li>The number of vowels is counted by iterating through the string and checking for characters a, e, i, o, u (in both uppercase and lowercase).</li>
        <li>The average word length is calculated by splitting the string into words and dividing the total length of all words by the number of words.</li>
    </ul>

Palindrome Checker (Ignoring Case and Spaces)

This hack will create a function that checks if a given string is a palindrome. It will ignore case and spaces, making it more flexible.

%%javascript

// JavaScript checkPalindrome function

function checkPalindrome() {
    // Step 1: Get the input value from the user
    const str = document.getElementById('inputString').value;
  
    // Step 2: Remove spaces and convert the string to lowercase
    const cleanStr = str.replace(/\s+/g, '').toLowerCase();
  
    // Step 3: Reverse the cleaned string
    const reversedStr = cleanStr.split('').reverse().join('');
  
    // Step 4: Compare the original cleaned string with the reversed string
    if (cleanStr === reversedStr && cleanStr.length > 0) {
      // Step 5: Display success message if it's a palindrome
      document.getElementById('result').textContent = `"${str}" is a palindrome!`;
    } else {
      // Step 6: Display a message if it's not a palindrome
      document.getElementById('result').textContent = `"${str}" is NOT a palindrome.`;
    }
  }