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;
}
CodePudding user response:
If you're going to use the substring() method to get the second half of the String constant, 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);
}
}
The result is as follows:
12345
345
CodePudding user response:
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) ;
}}
