This week's book giveaway is in the Other Languages forum.
We're giving away four copies of Functional Reactive Programming and have Stephen Blackheath and Anthony Jones on-line!
See this thread for details.
Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Return a String at index with charAt.

 
Lex van Rijswijk
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have two simple examples to support my question. I can't figure out why (1) is working while (2) isn't. In my opinion I use them the same way.

(1)

(2)

With the second one, I get an type mismatch error that says: Cannot convert from char to string. When I try to find an answer on internet I see the str declared as a var type in all examples. But it works with the first example. So what is the difference in the 'return line' of the code and why is the first working while the second isn't?

What am I missing? Thanks
 
John Jai
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch, Lex.

The '+' operator is overloaded to do concatenation if one of the arguments to it is a String. Hence str.charAt(str.length()-1) + mid + str.charAt(0) forms a String which is the return type of frontBack() method but str.charAt(0) returns a char which is incompatible return type for the front22() method.

You can read that here
 
Lex van Rijswijk
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
John Jai,

Thank you for your fast and clear reply. I've asked this question at some other fora but... lets just say their answers weren't helpfull or friendly in any way.

If I want to return a String in the second example it's better to use str.substring()? Or are there other possibilities?

 
John Jai
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, you can use the substring() method. Also you can use the valueOf(char) method to get the String representation of the character.
 
John Jai
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Lex van Rijswijk wrote:I've asked this question at some other fora but...

As you are new to ranch, please read this.
 
Lex van Rijswijk
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you, I'll give it a try!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic