Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

How would I remove letters at an even position throughout a string in Java?

        
        String evensRemoved = "";
        
        String str = reversedNames[1];
        
        String noSpaces = str.replace(" ","");
        
        int strlength = noSpaces.length();
        
        for(int i = 0; i <= strlength; i++){
            
            if(i % 2 == 0){
                StringBuilder sb = new StringBuilder(noSpaces);
                sb.deleteCharAt(i);
                
                String result = sb.toString();
                
                return result;
            }
        }
        
        return "";

I want to be able to remove letters at even positions throughout the string completely, and then return the string to the original method. I've looked at other solutions and haven't been able to figure it out at all. New to Java.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this.

  • It uses a regex that takes two chars at a time and replaces them with the 2nd, thus removing every other one.
  • the (.) is a capture group of 1 character.
  • $1 is a back reference to it.
   String s = "abcdefghijklmnopqrstuvwxyz";
   s = s.replaceAll("(?s).(.)?", "$1");
   System.out.println(s);

Prints

bdfhjlnprtvxz

per Andreas suggestion, I preceded the regex with a flag that lets . match returns and linefeeds.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...