如何在java中使用for循环连接两个字符串 [英] how to concatenate two strings using for loop in java
本文介绍了如何在java中使用for循环连接两个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好...
i想知道如何通过在java中使用for循环来控制或组合字符串...
hi everyone...
i want to know how to con-cat or combine strings by using for loop in java...
推荐答案
当你只想连接2个字符串时不需要循环:
No need for loop when you just want to concatenate 2 strings:
String firstString = "Hello";
String secondString = "World";
String sayHello = firstString + " " + secondString;
了解更多信息: http://www.tutorialspoint.com/java/java_strings.htm [ ^ ]
答案是:使用+运算符。或者,您可以使用String
方法String concat(String)
: http://docs.oracle.com/javase/7/docs/api/java /lang/String.html#concat(java.lang.String) 。
使用for循环部分根本没有意义。无论您需要什么,都可以使用循环,不要将不同的东西混合在一起。当你问一个如何的问题时,你不应该把它与你理解如何这个问题混在一起。
-SA
The answer is: using '+' operator. Alternatively, you can use theString
methodString concat(String)
: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#concat(java.lang.String).
The "using for loop" part simply makes no sense. Do with your loop whatever you need to, don't mix different things together. When you ask a "how to" question, you should not mix it with you understanding of "how" to do it.
—SA
这里你的解决方案,,,
Here your solution,,,
public static void main(String[] args) {
String str1 = "Ajith ";
String str2 = "Kp";
int n1 = str1.length();
int n2 = str2.length();
char[] chr = new char[n1+n2];
int ind = 0;
for(int i=0;i<n1;i++)
{
chr[ind] = 0;
chr[ind++] = str1.charAt(i);
}
for(int i=0;i<n2;i++)
{
chr[ind] = 0;
chr[ind++] = str2.charAt(i);
}
String str = String.valueOf(chr);
System.out.println(str);
}
这篇关于如何在java中使用for循环连接两个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文