Interview Question
Country: United States
Is this what you mean?
Scanner br = new Scanner(new InputStreamReader(System.in));
String s = br.nextLine();
int length = s.length();
System.out.println(s.substring(0, length/2)+s.charAt(length-2)+s.charAt(length-1)+s.substring(length/2, length));
Enter String:
Console Input: hi this is a test
Console Output: hi this stis a test
If you don't want the last two letters then just modify the substring.
import java.util.Scanner;
public class halfword
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("enter a string");
String str = scan.next();
int len = str.length();
String substring = str.substring(0,len/2);
System.out.println(substring);
substring = str.substring(len-2);
System.out.println(substring);
substring = str.substring(len/2);
System.out.println(substring);
}
}
import java.util.Scanner;
public class halfword
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("enter a string");
String str = scan.next();
int len = str.length();
String substring = str.substring(0,len/2);
System.out.println(substring);
substring = str.substring(len-2);
System.out.println(substring);
substring = str.substring(len/2);
System.out.println(substring);
}
}
public class SplitString{
public static void main(String[] args){
String in="TestThisWithSubstring";
int cnt=in.length();
String lasthalfStr=in.substring(cnt/2);
String lastTwoChar=in.substring(cnt-2);
String firstHalfStr=in.substring(0,cnt/2);
System.out.println("first half:"+firstHalfStr);
System.out.println("last two:"+lastTwoChar);
System.out.println("Last half:"+lasthalfStr);
}
}
how to code this? can i get your help?
- mich February 15, 2017