-2

Before you ask, yes I did Google this first. I haven't found a proper answer yet. I understand the syntax for a String array in a for loop, but not for a String. For example, let's say I have a fragment code which includes a for loop that's purpose is to adjust an element of the String to "josh" if that element isn't equal to something (I can't think of anything at the top of my head). The fragment code would be like this:

public void adjustScore(String[] str){
    for(int j= 0; j < str.length; j++){
        if(str[j] != //idk, something//
        str[j]= "josh";
        }
    else{};
}

But, how would this look if it was a String instead of a String[]?

public void adjustScore(String str2){
    for(int j=0; j < str2.length(); j++){
    // How do I call an element from the String? Would I still use str2[j]?//
user123
  • 17
  • 5
  • Possible duplicate of [What is the easiest/best/most correct way to iterate through the characters of a string in Java?](http://stackoverflow.com/questions/196830/what-is-the-easiest-best-most-correct-way-to-iterate-through-the-characters-of-a) – scrappedcola Apr 25 '17 at 22:52
  • 2
    Define "element" in a `String`. A string consists of *characters*, so your loop with indexes over the `length()` of the string would likely call `atr2.charAt(i)` to get a `char` value. Don't know how that relates to the "josh" you're talking about. – Andreas Apr 25 '17 at 22:53

1 Answers1

2

In Java, a String is not an array of characters. Although it is true that the only "elements" in a String are characters, you can use String.charAt(int) to get a character at a valid index (but you cannot use []).

char ch = str2.charAt(j);
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • 1
    Thank you! I post my question and within seconds I get bombarded with thumbs downs. This is why I hate coming here for help, everyone is so mean. THANK YOU SO MUCH for not being rude and actually helping me!! You rock!! – user123 Apr 25 '17 at 22:56
  • @OusmaneMahyDiaw Lol, that's because the first thing people want to nag me about is "You should really Google this first." or "Look it up online." and then proceed to not give me ANY help, report my question, and eventually have it deleted. Although questions online might be *similar* to what I ask, the answers provided didn't have what I was looking for. LOL and now it's put on hold for being "unclear". Dude, i gave a perfect explanation and example. *shakes my head*, I must have been desperate to come here. Full of bullies. – user123 Apr 25 '17 at 23:06