Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing a string to match a char array [duplicate]

I'm very inexperienced in programming, so bear with me.

I have to write a class that mimics some attributes of the String class. In this particular method, I have to take a char array and get a string to match it.

This is what I have so far:

1 char[] word = new char[80];
2 int wordLength = word.length;    
3
4 public String getString () {
5      String s;
6      s.length() = word.length;
7      for (int i = 0; i < word.length; i++) {
8           s.charAt(i) = word[i];
9      }
10     return s; 
11 }

I should mention that the char array is null here, but in the main method, values are assigned to it.

This is the error I'm getting at lines 6 and 8:

The left-hand side of an assignment must be a variable

I have no idea why it isn't recognizing String s as a variable.

like image 529
Ryan Avatar asked Dec 03 '22 16:12

Ryan


2 Answers

I'm not sure if you are allowed to use that, but you can create a String from a char array like this:

String s = new String(charArray);

Now to your code:

String s;
s.length() = word.length;

Two problems here, first s is not initialized, before you can do anyting with it, you need to assign a value to it:

String s = new String();

Since this creates a completely new String it is better to use the following code, since Strings are chached:

String s = "";

Next String is a immutable class, which means you can't change any attributes, once it is created. Plus s.length() returns an int value and NO pointer/reference, which means you can't assign a new value to it like that. Same goes with

s.charAt(i) = word[i];

its simply not possible.

To create a String char by char you can do something like this:

String s = "";
for (char c : charArray)
{
    s += c;
}

Note that s += c creates a new String each time.

Better to use a StringBuilder:

StringBuilder s = new StringBuilder();
for (char c : charArray)
{
    s.append(c);
}
s.toString();

And again, you could do that in one line:

String s = new StringBuilder().append(charArray).toString();
like image 170
Pinkie Swirl Avatar answered Dec 14 '22 11:12

Pinkie Swirl


The error is here:

s.length() = word.length;
s.charAt(i) = word[i];    // same here

You are trying to assign the length to the return value of length method.

Also note that, String s, is uninitialized.

The simplest form of getString() will look like this:

public String getString () {
  String s = "";
  for (int i = 0; i < word.length; i++) {
    s = s + word[i];
  }
  return s;
}

It would be better to use StringBuilder instead of string concatenation.

public String getString () {
  StringBuilder builder = new StringBuilder();
  for (int i = 0; i < word.length; i++) {
    builder.append(word[i]);
  }
  return builder.toString();
}
like image 21
YoungHobbit Avatar answered Dec 14 '22 09:12

YoungHobbit