开发者

Java loop-output fact [closed]

开发者 https://www.devze.com 2023-04-09 03:43 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying 开发者_如何转开发this question so that it can be reopened, visit the help center. Closed 11 years ago.

Think about the code below has a loop article.length

public String getArticle(){

String headline=article.getHeadline(); //getting a,b,c,d from here
System.out.println(article) 
return blabla;

 }

Lets say output is like:

1-a 2-a 3-b 4-c 5-d 6-d

What is the way of writing output like:

1-a 2-b 3-c 4-d

"I want to remove duplicate characters from a string"


If I understand you correctly, you want to count each character in a String?

  • Create a map to store the character counts
  • Iterate over the string
  • For each character, add 1 to the current character count (or store 1 if this is the first occurrence)
  • Print/use your results from the map

Edit: After reading your question again, I now think your want to remove duplicate characters from a string?


To keep only the first occurrence of each character in a string, you could do the following:

public String nubChars( String s ) {
    final StringBuilder sb = new StringBuilder();
    final Set<Character> cs = new HashSet<Character>();
    final int length = s.length();
    for( int i = 0; i < length; i++ ) {
        final Character c = s.charAt( i );
        if( cs.add( c ) ) {
            sb.append( c );
        }
    }
    return sb.toString();
}

When passed a string like hello world this method would return helo wrd.

Is this what you need?

0

精彩评论

暂无评论...
验证码 换一张
取 消