简体   繁体   English

替换字符串的第n个字符但忽略空格的最佳方法?

[英]Best way to replace nth character of a string but ignores white space?

I'm trying to figure out the best way to replace the nth character of a string but ignore the space when looping. 我试图找出最好的方法来替换字符串的第n个字符,但在循环时忽略空格。 For example, if I was to change every 5th character of the String mary had a little lamb to z , it should return mary zad azlittze lazb 例如,如果我要更改字符串mary had a little lamb每第5个字符,将z mary zad azlittze lazb mary had a little lamb ,则应返回mary zad azlittze lazb

One way I thought would be to remove all space ( maryhadalittlelamb ), then change all the 5th character to z ( maryzadazlittzelazb ) and then reference the original string, find the index of " " and insert it into maryzadazlittzelazb 我认为的一种方法是删除所有空格( maryhadalittlelamb ),然后将所有第5个字符更改为zmaryzadazlittzelazb ),然后引用原始字符串,找到" "的索引并将其插入maryzadazlittzelazb

But this doesn't seem very elegant and I'm sure theres a better way to do this, could someone please advise? 但这似乎不太优雅,我敢肯定有更好的方法可以做到这一点,请有人指教吗?

Thanks! 谢谢!

I would use String.toCharArray() , then iterate with a regular for loop and test if each character is not whitespace with Character.isWhitespace(char) . 我将使用String.toCharArray() ,然后使用常规的for循环进行迭代,并使用Character.isWhitespace(char)测试每个字符是否不是空格。 If it's not, increment the second counter (here named p ) and check if that value is divisible by five. 如果不是,请增加第二个计数器(在此称为p ),并检查该值是否可被5整除。 If so, set it to z . 如果是这样,请将其设置为z Finally, create a new String based on the edited char[] . 最后,基于编辑的char[]创建一个新的String Like, 喜欢,

String str = "mary had a little lamb";
char[] arr = str.toCharArray();
for (int i = 0, p = 0; i < arr.length; i++) {
    if (!Character.isWhitespace(arr[i]) && ++p % 5 == 0) {
        arr[i] = 'z';
    }
}
System.out.println(new String(arr));

I get (as I mentioned in the comments) 我得到了(正如我在评论中提到的)

mary zad a lzttle zamb

Also, because it might not be very clear, the complex if above is equivalent to 此外,因为它可能不是很清晰,复杂的if上面是相当于

if (!Character.isWhitespace(arr[i])) {
    p++;
    if (p % 5 == 0) {
        arr[i] = 'z';
    }
}

For completeness, my suggestion would have looked like this: 为了完整起见,我的建议应如下所示:

public static void main(String... args) {
  Pattern p = Pattern.compile("((\\S\\s*){4})\\S");
  Matcher m = p.matcher("mary had a little lamb");
  StringBuffer sb = new StringBuffer();
  while (m.find()) {
    m.appendReplacement(sb, "$1z");
  }
  m.appendTail(sb);
  System.out.println(sb.toString()); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM