[英]Remove first half of string using for loop
Variable message
is the user inputed string.可变message
是用户输入的字符串。 How do I make the substring run only to half.如何使 substring 只运行到一半。
public void deleteHalf(){
String del = "";
for ( int i=message.length(); i>=0; i++)
del += message.substring(i,i-1);
message = del;
}
If you're going to use the substring()
method to get the second half of the string expression, you don't need to use a for loop:如果要使用substring()
方法获取字符串表达式的后半部分,则不需要使用 for 循环:
public class HelloWorld
{
public static void main(String []args)
{
String text = "12345";
System.out.println(text);
System.out.println(deleteHalf(text));
}
public static String deleteHalf(String message)
{
return message.substring(message.length()/2, message.length()) ;
}
}
The result is as follows:结果如下:
12345
345
Even though your current logic says that you want to store the last part, I still want to know whether you want to delete the front half or the second half.即使您当前的逻辑说您要存储最后一部分,我仍然想知道您是要删除前半部分还是后半部分。 Based on that, you can use the following methods,基于此,您可以使用以下方法,
public class HelloWorld{
public static void main(String []args){
String s = "result";
System.out.println("result");
System.out.println(deleteFirstHalf(s));
System.out.println(deleteSecondHalf(s));
}
private static String deleteFirstHalf(String s){
return s.substring(s.length()/2) ;
}
private static String deleteSecondHalf(String s){
return s.substring(0,s.length()/2) ;
}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.