Java程序中偶数索引出现的问题

huangapple go评论76阅读模式
英文:

Problem with even indexes in Java program

问题

这个方法接受两个参数(字符串,字符),如果索引是偶数,则将字符串中的字符替换为 '+',如果索引是奇数,则替换为 '#'

我使用的字符串是 "Mary Bella Abracadabra",预期的输出是 "M+ry Bell+ +br#c#d#br+"。但实际输出是 "M#ry Bell# #br#c#d#br#"

我找不到代码中的错误。似乎所有包含字符 ch 的索引都是奇数。

public String emphasize(String phrase, char ch) {
    String phraseEmph = "";
    char c1 = '#';
    char c2 = '+';
    for (int i = 0; i < phrase.length(); i++) {
        char c = phrase.charAt(i);
        char cc = Character.toLowerCase(c);
        if ((cc == ch) && ((i % 2) == 0)) {
            phraseEmph = phrase.replace(c, c2);
            phrase = phraseEmph;
        } else if ((cc == ch) && ((i % 2) != 0)) {
            phraseEmph = phrase.replace(c, c1);
            phrase = phraseEmph;
        }
        phrase = phrase;
    }
    return phrase;
}

public void testEmphasize() {
    String phrase = "Mary Bella Abracadabra";
    char ch = 'a';
    String Emphasized = emphasize(phrase, ch);
    System.out.println("Emphasized: " + Emphasized);
}
英文:

The method takes 2 parameters (String,char) and returns the string with the char replaced by &#39;+&#39; if index is even and &#39;#&#39; if index is odd.

The String I use is &quot;Mary Bella Abracadabra&quot; and the expected output is &quot;M+ry Bell+ +br#c#d#br+&quot;. Instead I get &quot;M#ry Bell# #br#c#d#br#&quot;.

I can't find the error in my code. It seems that all indexes where char ch is found are odd.

public String emphasize (String phrase, char ch){
    String phraseEmph = &quot;&quot;;
    char c1 = &#39;#&#39;;
    char c2 = &#39;+&#39;;
    for (int i=0; i &lt; phrase.length(); i++){
         char c = phrase.charAt(i);
         char cc = Character.toLowerCase(c);
         if ((cc == ch) &amp;&amp; ((i % 2) == 0)){
            phraseEmph = phrase.replace(c,c2);
            phrase = phraseEmph;   
            }
         else if ((cc == ch) &amp;&amp; ((i % 2)!= 0)){
            phraseEmph = phrase.replace(c,c1);
            phrase = phraseEmph;   
            }  
         phrase = phrase; 
    }
    return phrase;
}

public void testEmphasize(){
    String phrase = &quot;Mary Bella Abracadabra&quot;;
    char ch = &#39;a&#39;;
    String Emphasized = emphasize(phrase,ch);
    System.out.println(&quot;Emphasized : &quot; + Emphasized);
}

答案1

得分: 3

当你调用replace函数时,它不仅会替换当前的'a',而是会替换所有这些'a'。你需要找到一种不同的方法来替换字符,这样你每次只改变一个字符。

(我故意避免提供修复建议。如果你自己想出解决方法,会更有教育意义。)

英文:

When you call replace it doesn't just replace the current &#39;a&#39;, it replaces all of them. You'll need to find a different way to replace characters so that you only change one at a time.

<sup>(I've purposefully avoided suggesting a fix. It'll be more educational if you come up with it yourself.)</sup>

答案2

得分: 1

注意,在Java中数组从0开始。字符串是不可变的,不提供太多可变方法。最好使用StringBuilder,如下所示,既方便又节省内存。

public static String emphasize(String phrase, char ch) {
    StringBuilder phraseEmph = new StringBuilder(phrase);
    char c1 = '#';
    char c2 = '+';
    for (int i = 0; i < phrase.length(); i++) {

        char c = phrase.charAt(i);
        char cc = Character.toLowerCase(c);
        if ((cc == ch) && ((i % 2) == 0)) {
            phraseEmph.setCharAt(i, c2);
        } else if ((cc == ch) && ((i % 2) != 0)) {
            phraseEmph.setCharAt(i, c1);
        }
    }
    return phraseEmph.toString();
}
英文:

Note Array start with 0 in java. String is immutable and don't provide many mutable methods. It's best to make use of StringBuilder as shown below both for easiness and memory efficiency.

	public static String emphasize(String phrase, char ch) {
	StringBuilder phraseEmph = new StringBuilder(phrase);
	char c1 = &#39;#&#39;;
	char c2 = &#39;+&#39;;
	for (int i = 0; i &lt; phrase.length(); i++) {

		char c = phrase.charAt(i);
		char cc = Character.toLowerCase(c);
		if ((cc == ch) &amp;&amp; ((i % 2) == 0)) {
			phraseEmph.setCharAt(i, c2);
		} else if ((cc == ch) &amp;&amp; ((i % 2) != 0)) {
			phraseEmph.setCharAt(i, c1);
		}
	}
	return phraseEmph.toString();
}

答案3

得分: 1

这里有一些建议。

  • 使用 StringBuilder 来进行字符替换。初始化为原始字符串。然后可以使用 setCharAt 进行更改。
  • 结合 toLowerCase 使用 indexOf。然后就不需要验证是否找到了字符,只需使用返回的索引,如果索引为 -1,则返回最终字符串。
  • 然后只需检查偶数索引或奇数索引,就像你正在做的那样,但是赋值给一个临时字符变量。
  • 然后使用该变量来替换字符。就像这个伪代码
    char repl;
    if (even) {
       repl = '#';
    } else {
       repl = '+';
    }
    进行替换操作
  • 不要对偶数索引和奇数索引都进行检查。只需检查一个条件,否则就必须是另一个条件(无需再次检查)。

除了我的建议,这里是另一种方法。

主要区别在于它使用偶数/奇数的结果来索引数组以替换字符。

public static String emphasize(String phrase, char ch) {
    StringBuilder sb = new StringBuilder(phrase);
    char[] chars = { '#', '+' };
    int idx = -1;
    while ((idx = phrase.toLowerCase().indexOf(ch, idx + 1)) >= 0) {
        sb.setCharAt(idx, chars[idx % 2]);
        phrase = sb.toString();
    }
    return phrase;
}
英文:

Here are some suggestions.

  • use a StringBuilder to make the character replacements. Intialize to the original string. You can then use setCharAt to make the change.
  • Use indexOf in conjunction with toLowerCase. Then you don't need to verify if you found the character, just use the index returned and return the final string if -1.
  • then just check for even or or indices like you are doing but assign to a holding char variable.
  • Then use that to replace the character. Like this pseudocode
    char repl;
    if (even) {
       repl = &#39;#&#39;;
    } else {
       repl = &#39;+&#39;;
    }
    make replacement
  • don't do a check for both even or odd. Just check for one condition, Otherwise it must be the other condition (not need to check again).

Aside from my recommendations, here is another way of doing it.

The main difference is that it uses the even/odd result to index into the array to replace the character.

public static String emphasize(String phrase, char ch) {
	StringBuilder sb = new StringBuilder(phrase);
	char[] chars = { &#39;#&#39;, &#39;+&#39; };
	int idx = -1;
	while ((idx = phrase.toLowerCase().indexOf(ch, idx + 1)) &gt;= 0) {
		sb.setCharAt(idx, chars[idx % 2]);
		phrase = sb.toString();
	}
	return phrase;
}    

</details>



# 答案4
**得分**: 1

```java
使用 `StringBuilder` 而不是 `String` 来在循环内连接字符串,因为它速度更快且消耗的内存较少。
在比较之前,将两个字符都转换为相同的大小写(例如小写)。这样,无论以任何大小写形式将字符传递给函数,都可以进行比较。
在这种情况下,不应使用 `String#replace`,因为它会替换被替换字符串/字符在字符串中的所有出现。

**示例:**

```java
public class Main {
    public static void main(String[] args) {
        // 测试
        System.out.println(emphasize("Mary Bella Abracadabra", 'a'));
        System.out.println(emphasize("Mary Bella Abracadabra", 'A'));
    }

    public static String emphasize(String phrase, char ch) {
        char c1 = '#';
        char c2 = '+';
        StringBuilder sb = new StringBuilder();

        // 将字符参数转换为小写
        char chLower = Character.toLowerCase(ch);

        for (int i = 0; i < phrase.length(); i++) {
            char c = phrase.charAt(i);
            if (Character.toLowerCase(c) == chLower) {
                if (i % 2 == 0) {
                    sb.append(c1);
                } else {
                    sb.append(c2);
                }
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }
}

输出:

M+ry Bell+ +br#c#d#br+
M+ry Bell+ +br#c#d#br+
英文:
  1. Use StringBuilder instead of String for concatenation to a string inside a loop because it is much faster and consumes less memory.
  2. Convert both the characters in the same case (e.g. lowercase) before comparing. This way, you can pass the character to the function in any case.
  3. You should not use String#replace for this case as it replaces all occurrences of replacement character/string in the string being replaced.

Demo:

public class Main {
	public static void main(String[] args) {
		// Test
		System.out.println(emphasize(&quot;Mary Bella Abracadabra&quot;, &#39;a&#39;));
		System.out.println(emphasize(&quot;Mary Bella Abracadabra&quot;, &#39;A&#39;));
	}

	public static String emphasize(String phrase, char ch) {
		char c1 = &#39;#&#39;;
		char c2 = &#39;+&#39;;
		StringBuilder sb = new StringBuilder();

		// Convert the char parameter to lower case
		char chLower = Character.toLowerCase(ch);

		for (int i = 0; i &lt; phrase.length(); i++) {
			char c = phrase.charAt(i);
			if (Character.toLowerCase(c) == chLower) {
				if (i % 2 == 0) {
					sb.append(c1);
				} else {
					sb.append(c2);
				}
			} else {
				sb.append(c);
			}
		}
		return sb.toString();
	}
}

Output:

M+ry Bell+ +br#c#d#br+
M+ry Bell+ +br#c#d#br+

答案5

得分: 0

你的代码效率很低,我的建议:

class emphasize {
    private String phrase;
    private char ch;
    public emphasize(String phrase, char ch) {
        this.phrase = phrase;
        this.ch = ch;
    }
    public String execute() {
        char chars[] = phrase.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            /* 由于char是基本数据类型,我可以使用== */
            if (chars[i] == Character.toLowerCase(ch) || chars[i] == Character.toUpperCase(ch))
                chars[i] = i % 2 == 0 ? '+' : '#';
        }
        return String.valueOf(chars);
    }
}
public class Main {
    public static void main(String[] args) {
        String phrase = "Mary Bella Abracadabra";
        char ch = 'a';
        emphasize obj = new emphasize(phrase, ch);
        System.out.println(obj.execute());
    }
}

输出:

Java程序中偶数索引出现的问题

英文:

Your code is very inefficient, my suggestion :

class emphasize {
    private String phrase;
    private char ch;
    public emphasize(String phrase, char ch) {
        this.phrase = phrase;
        this.ch = ch;
    }
    public String execute() {
        char chars[] = phrase.toCharArray();
        for (int i = 0 ; i &lt; chars.length ; i++) {
            /* As char is primitive type I can use == */
            if (chars[i]==Character.toLowerCase(ch) || chars[i]==Character.toUpperCase(ch)) chars[i] = i%2==0 ? &#39;+&#39; : &#39;#&#39;;
        }
        return String.valueOf(chars);
    }
}
public class Main {
    public static void main(String[] args) {
        String phrase = &quot;Mary Bella Abracadabra&quot;;
        char ch = &#39;a&#39;;
        emphasize obj = new emphasize(phrase, ch);
        System.out.println(obj.execute());
    }
}

Output :

Java程序中偶数索引出现的问题

答案6

得分: 0

public class Main {
    public static void main(String[] args) {
        String phrase = "Maryaa Bella Abracadabra";
        char ch = 'a';
        System.out.println("Original   : " + phrase);
        String Emphasized = emphasize(phrase, ch);
        System.out.println("Emphasized : " + Emphasized);
    }
    
    public static String emphasize(String phrase, char ch) {
        StringBuilder temp = new StringBuilder(phrase); 
        char c1 = '#';
        char c2 = '+';
        for (int i = 0; i < phrase.length(); i++) {
            char c = phrase.charAt(i);
            char cc = Character.toLowerCase(c);
            if (cc == ch) {
                if (i % 2 == 0) {
                    temp.setCharAt(i, c1);
                } else {
                    temp.setCharAt(i, c2);
                }
            }
        }
        return temp.toString();
    }
}

Output:

Original   : Maryaa Bella Abracadabra
Emphasized : M+ry#+ Bell+ +br#c#d#br+
英文:

Full tested simplified code :

public class Main {
	public static void main(String[] args) {
	    String phrase = &quot;Maryaa Bella Abracadabra&quot;;
        char ch = &#39;a&#39;;
        System.out.println(&quot;Original   : &quot; + phrase);
        String Emphasized = emphasize(phrase,ch);
        System.out.println(&quot;Emphasized : &quot; + Emphasized);
	}
	
	public static String emphasize (String phrase, char ch){
        StringBuilder temp = new StringBuilder(phrase); 
        char c1 = &#39;#&#39;;
        char c2 = &#39;+&#39;;
        for (int i = 0; i &lt; phrase.length(); i++){
             char c  = phrase.charAt(i);
             char cc = Character.toLowerCase(c);
             if(cc == ch) {
                 if(i%2 == 0){
                     temp.setCharAt(i, c1);
                 } else {
                     temp.setCharAt(i, c2);
                 }
             }
        }
        return temp.toString();
    }
		
}

Output :

Original   : Maryaa Bella Abracadabra                                                                                                                          
Emphasized : M+ry#+ Bell+ +br#c#d#br+

huangapple
  • 本文由 发表于 2020年7月25日 00:24:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/63077648.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定