-
Concatinating a String
Just wondering is this the right way to go about creating a method that concatinates a string a certain number of times or is there a better way.
It doesnt look right to me, wont this loop just pring one sentance because it will be returned once, the loop is not actually adding them together.
Code:
public String concat(String sentance, int count)
{
for (int i = 0; i < count; i++) {
return sentance;
}
return sentance;
}
Thanx george
-
If you want to concatenate the same string over and over your method will only return it once or probably keep returning it the same way if there is no string that was initialized in the main class to catch it. Anyway, this is what ur method is supposed to look like
Code:
public String conc(String sentence , int count ) {
String s = null; // creating an empty string
for ( int i = 0 ; i < count ; i++ ) {
s = s +sentence ; // this will add ur string over over
}
return s; // finally it has been combined into one string and will return it
}
-
You are correct: that method only returns the original string. A simple way to concatinate a string would to place the following in the loop:
Code:
newSentance = newSentance + sentance;
and also do the following:
- Define the newSentance variables before the loop
- remove the return statement in the loop
Luck,
CJSL
-
Thanx both of you for the help.
I changed the code and think this is the right idea:
Code:
public String concat(String sentance, int count)
{
String newSentance = null;
for (int i = 0; i < count; i++) {
newSentance += sentance;
}
return newSentance;
}
-
You can also use the StringBuffer and StringBuilder class to cancatinate the string.
Code:
StringBuffer buffer = new StringBuffer();
buffer.append("abc");
buffer.append("def");
buffer.append("ghi");