character within a string

string [] name={"name1","name2","name3"};

how do i address characters in string? name[0][4] should be 1 name[1][4] should be 2 what is the proper syntax, this worked in C

Answers

  • name[0].charAt(4) == '1'
    name[1].charAt(4) == '2'
    name[2].charAt(4) == '3'
    
  • name[1].charAt(charcnt)=key; gives 'Left hand side of assignment must be a variable' error ? name is a string, charcnt is int, key is from keyPressed()

  • Use 2

    ==

  • Answer ✓

    assign is =

    Compare is ==

  • I want to assign the 'key' character returned from keyPressed to a location in the string. charcnt increments to position where the character goes in the string. I am trying to build a string from key board input, a simple data entry routine for a filename in a box using keyPressed()

  • I see

    Sorry

  • Answer ✓

    You didn't make it clear that you wanted to assign values to a particular position in the String. C does not have a String data type it uses char arrays instead which makes it easier to assign individual characters, Java does not have anuthing similar. The best way would be to create your own function to do it e.g.

    String replaceChar(String s, int pos, char ch){
      if(pos >0 && pos < s.length()){
        char [] chars = s.toCharArray();
        chars[pos] = ch;
        return new String(chars);
      }
      return s; // invalid position
    }
    

    Then

    name[0] = replaceChar(name[0], 4, '?');

    would change "name1" to "name?"

  • i got it now

Sign In or Register to comment.