简体   繁体   中英

Remove first half of string using for loop

Variable message is the user inputed string. How do I make the substring run only to half.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM