# Strings

* Strings
* JUnit
* recursion

### reverse

```java
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

```java
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

```java
  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

```java
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

```java
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

```java
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

```java
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**

```java
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

![img](https://i0.wp.com/algorithms.tutorialhorizon.com/files/2019/08/RomanNumberTable.png?resize=209%2C313\&ssl=1)

* **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

```java
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](https://algorithms.tutorialhorizon.com/convert-integer-to-roman/)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://nissan-goldberg.gitbook.io/java101/lesson-6-strings-junit-and-recursion/untitled.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
