将字符串分成两半

Splitting a string into two halfs

我正在制作一个新的转换软件来隐藏消息(为了好玩)。我进行了二进制和十进制转换 class,我的想法是,用户输入字符串,它将全部转换为二进制格式。然后将它分成两半,将一半转换为十进制,然后再次将字符串加在一起,使其成为二进制和十进制的混合体。在其他版本中,我将添加更多转换、更多拆分,并且可能也会转换为语言。我需要将字符串分成两半。到目前为止,这是我的代码::

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.

    }
}

我想这会让你完成你想要实现的目标:

P.S。请注意,对于具有 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);
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的子字符串函数将它们分成两半:

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

试试这个:

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);
    }   
}