开发者

How To Delete String1 from String2 and build a new String2 with remaining string?

I have 2 String str1 and str2 and i want to build a updated str2 with the contents which character is not present inside the str1 without using inbuilt function of string. Str开发者_高级运维ing is as follows:

String str1="bdf";

String str2="abc gde fhi**";

and output should be like:

"ac ge hi";


I'd say use the inbuilt way to read from a string a an array of chars and a foreach loop to remove the included chars.

For c# it would look like this:

foreach(char c in  str1)
{
   str2.Replace(c,' ').Trim();
}

Of course you could also use indexes and str.Remove() to avoid spaces...

-EDIT sorry I just read you weren't allowed to use inbuilt functions - but reading from string as array is no function - every string is saved in memory as an array of chars - so this should be ok, only got to change the way to remove the chars:

String result;
int i=0;
foreach(char c in  str2)
{
   Bool isincluded = false;

   foreach(char c2 in str1)
   {
     if(c == c2) isincluded = true;
   }

   if(isincluded == false)
   { 
      result[i] = c;
      i++;
   }
}

isn't verified...but I hope it works :)


String removeCharsFromString(String fromString, String charsToBeRemoved) {
    BitSet charSet = new BitSet();
    for (char c : charsToBeRemoved.toCharArray())
        charSet.set(c);

    StringBuilder outputStr = new StringBuilder();
    for (char c : fromString.toCharArray())
        if (charSet.get(c) == false)
            outputStr.append(c);
    return outputStr.toString();
}


This is the full example. It's not the best effective you can get, but since you can't use functions made especially for your problem, this should work fine:

import java.util.*;
public class Test{
    public static void main(String[]args){
        String s1 = "abc def ghi"; // Source
        String s2 = "behi";           // Chars to delete 

        StringBuffer buf = new StringBuffer(s1); // Creates buffer (for deleteCharAt() func)

        for (int i=0; i<s2.length(); i++){ // For each letter in the delete-string 
            for (int j=0; j<s1.length(); j++){ // Test each letter in the source string
                if (s1.charAt(j)==s2.charAt(i)){ // Chars equal -> delete
                    buf.deleteCharAt(j);
                    s1=buf.toString(); // Updates the source string
                    j--;     // Moves back one position (else it would skip one char, due to its deleting)
                }
            }
        }
        System.out.println(buf.toString());
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜