如果我有两个字符串,Hello和Java。它们的大小不一样。如果我想连接它们但是通过省略字符使更大的字符串大小相同我将如何处理它?</ p>
例如。你好,Java将成为elloJava和Day,测试将成为DayTes。
到目前为止我所做的只是比较。打印文本是占位符
if (a.length() != b.length())
System.out.print("tt");
else
System.out.print("1");
我不知道从哪里开始。
答案 0 :(得分:2)
如果第一个String更长:
// omit characters from the start of the first String
System.out.print(a.substring(a.length-b.length)+b));
如果第二个字符串更长:
// omit characters from the end of the second String
System.out.print(a+b.substring(0,a.length));
答案 1 :(得分:1)
您可以使用String.substring
:
int minLength = Math.min(a.length(), b.length());
String concatenated = a.substring(a.length() - minLength) + b.substring(0, minLength);
答案 2 :(得分:0)
public class Test {
String a="Hello";
String b="Java";
public void addString()
{
int minLength = Math.min(a.length(), b.length());
String concatenated = a.substring(1, minLength+1) + b.substring(0, minLength);
System.out.print("concatenated: " +concatenated);
}
public static void main(String[] args) {
Test test=new Test();
test.addString();
}
}
O/P : concatenated : elloJava
答案 3 :(得分:0)
公共课测试{
String a="Hello";
String b="Java";
public void addString()
{
int minLength = Math.min(a.length(), b.length());
String concatenated = a.substring(1, minLength+1) + b.substring(0, minLength);
OR
字符串连接=((a + b).substring(1,a.length())+ b);
System.out.print("concatenated: " +concatenated);
}
public static void main(String[] args) {
Test test=new Test();
test.addString();
}
}
O / P:连接:elloJava