Przejdź do głównej zawartości

String-2 > mixString

Given two strings, a and b, create a bigger string made of the first char of a, the first char of b, the second char of a, the second char of b, and so on. Any leftover chars go at the end of the result.


mixString("abc", "xyz") → "axbycz"
mixString("Hi", "There") → "HTihere"
mixString("xxxx", "There") → "xTxhxexre"

Mix String:
dwa stringi o roznej dlugosci
Musimy przejsc loopem przez oba i zlozyc nowy string . aby miec pewnosc ze iterujemy po wszystkich char w stringu wybieramy dluzszy. Konieczne zadeklarowanie zmiennej String str ktora bedzie przechowywala kolejne char



public String mixString(String a, String b){
    
    String str = "";
    int len = 0;

    if (a.length() >= b.length())
    {
        len = a.length();
    } else
        len = b.length();

    for (int i = 0; i < len; i++)
    {

        if (i < a.length())
        {
            str += a.charAt(i);
        }

        if (i < b.length())
        {
            str += b.charAt(i);
        }

    }
    return str;
}

Komentarze

Popularne posty z tego bloga

Skrócony zapis if - instrukcja warunkowa java

Instrukcja warunkowa - warunek i rezultat. if (warunek) { jesli spełniony wykonań operacje i zwróć wynik; } warunek nie spełniony Możliwości skrócenia kodu instrukcji warunkowej if (i < 0) ? i-- : i++; Jeżeli i mniejsze od zera to i-- jezeli false to i++ if (i < 0) {     i--; } else {     i++; } Skrócony zapis instrukcji warunkowej else if (i < 0) ? i--;  inna_zmienna=4; : i++; if (i < 0) {     i--; } else {     i++;     inna_zmienna = 4; } Skrócony zapis if

String-1 > endsLy

Given a string, return true if it ends in "ly". endsLy("oddly") → true endsLy("y") → false endsLy("oddy") → false public boolean endsLy ( String str ) { if ( str . length ()< 2 ){ return false ; } if (( str . substring ( str . length ()- 2 , str . length ())). equals ( "ly" )){ return true ; } return false ; }

String-1 > withouEnd2

Given a string, return a version without both the first and last char of the string. The string may be any length, including 0. withouEnd2("Hello") → "ell" withouEnd2("abc") → "b" withouEnd2("ab") → "" public String withouEnd2 ( String str ) { if ( str . length ()== 1 ){ return str . substring ( 1 ); } else if ( str . length ()== 0 ){ return str ; } return ( str . substring ( 1 , str . length ()- 1 )); }