If a challenge says that input will be in the form of a string, what is acceptable?
Various languages have different ways of implementing strings, so here's what I've "borrowed" from Wikipedia:
In computer programming, a string is traditionally a sequence of characters, either as a literal constant or as some kind of variable.
The reason I ask is that my most frequently used language here is Java. Of course, Java has a String
class, and that's what I've been using. However, I've run into a couple situations where a char[]
would be better.
In my opinion, while a char[]
is not a String
, it is a "string".
Say I have a challenge that reads:
Write a function that takes a string (printable ASCII) as input, adds 1 to each character, and returns it (don't worry about overflow)
While this is a trivial example, String
is crap here.
- It's not mutable, so I need a new one to return.
- To access a character you have to use
.charAt(i)
instead of[i]
.length()
is two bytes longer than.length
- Once you add, you have to cast it back to
char
or it converts to an integer:
An example of both types:
String a(String a){String b="";for(int i=0;i<a.length();b+=(char)(a.charAt(i++)+1));return b;}
char[]a(char[]a){for(int i=0;i<a.length;a[i++]++);return a;}
I haven't looked much to see if I can reduce either of these, but the point remains; there's no way the String
version is coming out ahead.
Of course, in some situations String
has the upper hand. If you need indexOf()
, trim()
, or easy conversion from literals, you'd want that.
Since both a String
and a char[]
are strings by most reasonable definitions of the word, I believe it shouldn't matter which is used. In addition, having to choose between the two makes for a different golf process than sticking to one or the other.
Don't get me wrong. I'm not saying that I've seen any argument/debate about this on the site, but I've personally held back from using char[]
where it asks for a string, and I just got around to wondering why. Either way, I think it would make a good Standard Definition, and I'd like some input.
char[]
with.toCharArray()
and then convert it back withnew String(carray)
? \$\endgroup\$