-2

我需要切断用户输入的字符串的一半。我已经尝试过了,但它没有用:

    Scanner sc = new Scanner(System.in);
    String nameOne = sc.nextLine();
    chars[] oneChars = new char[nameOne.length];
    double oneLength = oneChars.length / 2;
    Math.round(oneLength);
    int oneLen = (int)oneLength;
    String nameOneFinal = "";
    for(int i = 0; i == oneLen--; i++) {
        oneChars[i] = oneChars[oneLen];
        nameOneFinal = nameOneFinal + oneChars[i];
    }
4

4 回答 4

3
final int mid = nameOne.length() / 2;
String[] parts = {
    nameOne.substring(0, mid), // 1st part
    nameOne.substring(mid), // 2nd part
};
于 2013-05-15T06:47:04.187 回答
2

使用substring方法...你可以做到 例如:

public String extraEnd(String str) {

 String s = str.substring(str.length()/2);//it will have the last half of string 

 return s ;
}
于 2016-08-20T23:54:48.510 回答
0

使用SubString方法得到这个

String str = "CutThisBytwo";
int len = str.length();
String firstHalfStr = str.substring(0, len/2);
String secondHalfStr = str.substring(len/2,len );
System.out.println(firstHalfStr);
System.out.println(secondHalfStr);
于 2013-05-15T06:49:49.117 回答
-1

最简单的方法:使用String.substring(int index1, int index2)

艰难的道路:

String new = "";

for(int i = 0; (i < old.length() - 1) / 2; i++){

    new += old.charAt(i);

}

如果是为了做家庭作业,困难的方法可能会让你得到布朗尼积分,但如果不只是坚持简单的方法。

于 2013-05-15T06:58:47.463 回答