Strings

  • Strings

  • JUnit

  • recursion

reverse

package com.company;

import java.util.Scanner;


public class Main {
    public static String reverse(String str){
        String reversed = "";
        for (int i = 0; i < str.length(); i++)
            reversed = str.charAt(i) + reversed;

        return reversed;
    }

    public static void main(String[] args) {
        String str = "hello";
        System.out.println(reverse(str));
    }
}
olleh

JUnit

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import static com.company.Main.reverse;

public class MainTests {

    @Test
    void TestReverse() {
        Assertions.assertEquals("",reverse(""));
        Assertions.assertEquals("olleh",reverse("hello"));
        Assertions.assertEquals("dlrow olleh",reverse("hello world"));
    }
}
passed

version 2

  public static String reverse(String str){
        String reversed = "";
        for (char c : str.toCharArray())
            reversed = c + reversed;

        return reversed;
    }

JUnit on array

Lets add this function

public class Main {
    //added this function
    public static String[] reverse_strings(String[] strings){
        String[] r_strings = new String[strings.length];

        for (int i = 0; i < strings.length; i++) {
            r_strings[i] = reverse(strings[i]);
        }

        return r_strings;
    }

    //same as before
    public static String reverse(String str){
        String reversed = "";
        for (int i = 0; i < str.length(); i++)
            reversed = str.charAt(i) + reversed;

        return reversed;
    }

    public static void main(String[] args) {
        String[] strings = {"hello", "world"};
        reverse_strings(strings);
    }
}

and add some more tests

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import static com.company.Main.reverse;
import static com.company.Main.reverse_strings;

public class MainTests {

    @Test
    void TestReverse() {
        Assertions.assertEquals("dlrow olleh",reverse("hello world"));
    }

    @Test
    void TestReverseArray() {
        String[] strings = {"hello", "world"};
        Assertions.assertArrayEquals(new String[]{"olleh", "dlrow"},
                reverse_strings(new String[]{"hello", "world"}));
    }
}

here we used assertArrayEquals

Exercise - Permutations

public class Main {
    public static int occurances_of_char(String str, char c) {
        int count=0;
        for (int i = 0; i < str.length(); i++) {
            if(str.charAt(i) == c)
                ++count;
        }

        return count;
    }

    public static boolean permutation(String str1, String str2){
        if (str1.length()!=str2.length())
            return false;

        for (int i = 0; i < str1.length(); i++) {
            char curr_char = str1.charAt(i);
            if(occurances_of_char(str1, curr_char) != occurances_of_char(str2, curr_char))
                return false;
        }
        return true;
    }

    public static void main(String[] args) {
        String str = "hello";
        System.out.println(permutation(str, "lleho"));
        System.out.println(permutation(str, "llehol"));
        System.out.println(permutation(str, ""));
    }
}
true
false
false

version 2

since the version above is 0(n^2) it isn't very efficient, it would be better to use a bucket sort type of approach and that would give of 2*O(n)

Exercise: Remove words from String

Write a function that receives a string and 2 others string to be removed

remove2Strings("zzzabzzzabzzzabc", "ab", "c") -> returns -> "zzzzzzzzz"

solution

public class Main {
    public static void main(String[] args) {
        String str = remove2Strings("zzzabzzzabzzzabc", "ab", "c");
        System.out.println(str);

        str = removeManyStrings("zzzabzzzbczzze", "ab", "bc", "e");
        System.out.println(str);
    }

    public static String remove2Strings(String str, String getRidOf1, String getRidOf2) {
        String res = str.replace(getRidOf1, "").replace(getRidOf2, "");
        return res;
    }

    //... - means many args
    public static String removeManyStrings(String str, String... args) {
        String res = str;
        for(int i = 0; i < args.length; i++){
            res = res.replace(args[i], "");
        }

        return res;
    }
}
zzzzzzzzz
zzzzzzzzz

String... args - means there are an unknow amount of Strings (an array of Strings)

Exercise: Calculate the sum of the numbers appear in a given string

string 12 with120  20numbers -> returns 152

Solution

public class Main {
    public static int sumOfTheNumbers(String str) {
        int len = str.length();
        int sum = 0;
        String temp = "";

        for (int i = 0; i < len; i++) {
            //Character.isDigit() - Determines if the specified character is a digit.
            if (Character.isDigit(str.charAt(i))) {
                //if next char is also a digit, append
                if (i < len-1 && Character.isDigit(str.charAt(i+1))) {
                    temp += str.charAt(i);
                } else {  //if next char isn't a digit (but this char is) or end of the string
                    temp += str.charAt(i);
                    sum += Integer.parseInt(temp);
                    temp = "";
                }
            }
        }
        return sum;
    }

    public static void main (String[] args) {
        String str1 =  "this 12 is120 a string 20with numbers";
        System.out.println("The given string is: "+str1);
        System.out.println("The sum of numbers in the string is: "+ sumOfTheNumbers(str1));
    }
}
The given string is: this 12 is120 a string 20with numbers
The sum of numbers in the string is: 152

Exercise: Convert Int to Roman

  • I can be placed before V or X, represents subtract one, so IV (5-1) = 4 and 9 is IX (10-1)=9.

  • X can be placed before L or C represents subtract ten, so XL (50-10) = 40 and XC (100-10)=90.

  • C placed before D or M represents subtract hundred, so CD (500-100)=400 and CM (1000-100)=900.

for example

4   -> returns -> IV
25  -> returns -> XXV
400 -> returns -> CM

Solution

public class Main {

    public static String intToRoman(int num) {

        System.out.println("Integer: " + num);
        int[] values =           {1000, 900, 500, 400,  100, 90,   50, 40,  10,  9,   5,  4,  1};
        String[] romanLiterals = {"M", "CM", "D", "CD", "C", "XC","L","XL","X","IX","V","IV","I"};

        //StringBuilder represents a mutable sequence of characters.
        //String Class creates an immutable sequence of characters,
        StringBuilder roman = new StringBuilder();

        for(int i=0;i<values.length;i++) {
            while(num >= values[i]) {
                num -= values[i];
                roman.append(romanLiterals[i]);
            }
        }
        return roman.toString();
    }

    public static void main(String[] args) {
        System.out.println(intToRoman(25)  + "\n");
        System.out.println(intToRoman(1023)+ "\n");
        System.out.println(intToRoman(511) + "\n");
    }
}
Integer: 25
XXV

Integer: 1023
MXXIII

Integer: 511
DXI

Source

Last updated