簡體   English   中英

將一個字符串分成兩半

[英]Splitting a string into two halfs

我正在制作一個新的轉換軟件來隱藏消息(為了好玩)。 我做了一個二進制和十進制轉換類,我的想法是,用戶輸入字符串,它將所有轉換為二進制格式。 然后將其分成兩半,將一半轉換為十進制,然后再次將字符串相加,使其成為二進制和十進制的混合。 在其他版本中,我將添加更多轉換、更多拆分,並且也可能轉換為語言。 我需要將字符串分成兩半。 到目前為止,這是我的代碼::

public ray() {
    Scanner in = new Scanner(System.in);

    while (true) {
        System.out.println("Please input the text you wish to encode!");
        System.out.println("Type '#' to quit the Software.");
        String s1 = in.nextLine();
        if ("#".equalsIgnoreCase(s1)) {
            System.out.println("Goodbye, hope you enjoyed RAYConversion v1.0 Alpha.");
            // close software
        }

        // convert all to binary
        binary Binary = new binary();

        //what i need to do is split stirng s1 in half, make it into different strings. Then I will convert
        //the two strings to binary and decimal. I made a converter for that.

    }
}
final int mid = s1.length() / 2; //get the middle of the String
String[] parts = {s1.substring(0, mid),s1.substring(mid)};
System.out.println(parts[0]); //first part
System.out.println(parts[1]); //second part

您可以使用 Java 的 substring 函數將它們分成兩半:

String s1a = s1.substring(0, (s1.length()/2));
String s1b = s1.substring((s1.length()/2);

我想這會讓你完成你想要實現的目標:

PS請注意,對於具有odd個字符的字符串,后半字符串將獲得額外字符的好處。

創建一個這樣的方法:

public static String substring(int a, int b, String temp) {
    String a = "";
    for(int i = a; i<b; i++) {
        char ch1 = temp.charAt(i);
        a = a + ch1;
    }
    return a;
}

在你的main函數中,調用如下方法:

String s1a = substring(0, (s1.length()/2), s1);
String s1b = substring((s1.length()/2),s1.length(), s1);

嘗試這個:

int len = whole.length();
String a = whole.substring(0, len / 2), b = whole.substring(len / 2);

這使用substring()方法。 對於奇數長度的String ,后半部分將長一個字符。

此方法刪除具有奇數長度的字符串的中間字符。 這是由else部分下半部分的2 + 1完成的。

public void method()
{
    Scanner sc = new Scanner(System.in);
    System.out.println("ENTER A STRING");
    original = sc.next();
    
    if(original.length()%2 == 0)
    {
        firsthalf =original.substring(0, original.length()/2);
        secondhalf = original.substring(original.length()/2);
        System.out.println(firsthalf);
        System.out.println(secondhalf);
    }
    else
    {
        firsthalf = original.substring(0, original.length()/2);
        secondhalf = original.substring(original.length()/2+1);
        System.out.println(firsthalf);
        System.out.println(secondhalf);
    }   
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM