Results 1 to 5 of 5
Thread: Concatinating a String
- 03-27-2009, 11:11 AM #1
Member
- Join Date
- Mar 2009
- Posts
- 18
- Rep Power
- 0
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.
Thanx georgeJava Code:public String concat(String sentance, int count) { for (int i = 0; i < count; i++) { return sentance; } return sentance; }-Long time no c-
-:eek:-
- 03-27-2009, 12:30 PM #2
Member
- Join Date
- Apr 2008
- Posts
- 42
- Rep Power
- 0
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
Java 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 }
- 03-27-2009, 12:34 PM #3
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:
and also do the following:Java Code:newSentance = newSentance + sentance;
- Define the newSentance variables before the loop
- remove the return statement in the loop
Luck,
CJSLChris S.
Difficult? This is Mission Impossible, not Mission Difficult. Difficult should be easy.
- 03-27-2009, 01:19 PM #4
Member
- Join Date
- Mar 2009
- Posts
- 18
- Rep Power
- 0
Thanx both of you for the help.
I changed the code and think this is the right idea:
Java Code:public String concat(String sentance, int count) { String newSentance = null; for (int i = 0; i < count; i++) { newSentance += sentance; } return newSentance; }-Long time no c-
-:eek:-
- 03-30-2009, 01:34 PM #5
Member
- Join Date
- Mar 2009
- Posts
- 4
- Rep Power
- 0
Similar Threads
-
combine string[] into string like perl's join function
By tekberg in forum Advanced JavaReplies: 9Last Post: 02-23-2009, 01:05 PM -
Let eclipse warn about a semicolon after an if statement and string == string?
By foobar.fighter in forum EclipseReplies: 5Last Post: 01-11-2009, 10:12 AM -
Using java.util.Scanner to search for a String in a String
By Java Tip in forum Java TipReplies: 0Last Post: 11-20-2007, 04:59 PM -
Help with insertName(String name) and deleteName(String name)
By trill in forum New To JavaReplies: 1Last Post: 08-07-2007, 07:29 AM -
I can't seem to pass the value of a string variable into a string array
By mathias in forum Java AppletsReplies: 1Last Post: 08-03-2007, 10:52 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks