我需要切断一半用户输入的字符串。我试过这个并没有用:
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];
}
答案 0 :(得分:3)
final int mid = nameOne.length() / 2;
String[] parts = {
nameOne.substring(0, mid), // 1st part
nameOne.substring(mid), // 2nd part
};
答案 1 :(得分:2)
使用substring
方法......你可以做到
例如:
public String extraEnd(String str) {
String s = str.substring(str.length()/2);//it will have the last half of string
return s ;
}
答案 2 :(得分: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);
答案 3 :(得分:-1)
简单方法:使用String.substring(int index1, int index2)
艰难的道路:
String new = "";
for(int i = 0; (i < old.length() - 1) / 2; i++){
new += old.charAt(i);
}
如果是家庭作业,艰难的方式可能会让你获得布朗尼积分,但如果不是坚持简单的话。