19

Let's say I have a string obtained from a cursor,this way:

String name = cursor.getString(numcol);

and another String like this one:

String dest=cursor.getString(cursor.getColumnIndexOrThrow(db.KEY_DESTINATIE));

If finally I wanna obtain a String from the two of them,something like:

name - dest

Let say if name=Malmo and dest=Copenhagen

How could I finally obtain Malmo-Copenhagen???

Because android won't let me write :

name"-"dest
0

3 Answers 3

51

You need to use the string concatenation operator +

String both = name + "-" + dest;
Sign up to request clarification or add additional context in comments.

2 Comments

or use the String class method concat(). For example, name.concat("-").concat(dest) download.oracle.com/javase/6/docs/api/java/lang/String.html
@Jasonw - Calling concat twice is likely to be less efficient, as it creates an extra String object compared to how the compiler translates the in-line expression that Jon suggested. Also, Jon's solution is less typing. :)
15

The best way in my eyes is to use the concat() method provided by the String class itself.

The useage would, in your case, look like this:

String myConcatedString = cursor.getString(numcol).concat('-').
       concat(cursor.getString(cursor.getColumnIndexOrThrow(db.KEY_DESTINATIE)));

Comments

3

You can use concatenation operator and instead of declaring two variables only use one variable

String finalString =  cursor.getString(numcol) + cursor.getString(cursor.getColumnIndexOrThrow(db.KEY_DESTINATIE));

2 Comments

Btw "+" is the concatenation operator, and in case if your one of the value is not String then you need to cast it to String.
You'd only need to convert to a string if both values were non-strings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.