【问题标题】:How To Delete String1 from String2 and build a new String2 with remaining string?如何从 String2 中删除 String1 并用剩余的字符串构建一个新的 String2?
【发布时间】:2011-05-09 06:23:01
【问题描述】:

我有 2 个字符串 str1 和 str2,我想用 str1 中不存在的字符的内容构建一个更新的 str2,而不使用字符串的内置函数。 字符串如下:

String str1="bdf";

String str2="abc gde fhi**";

输出应该是这样的:

"ac ge hi";

【问题讨论】:

  • 使用哪种语言?为什么不使用字符串的内置函数?
  • 因为这是一个家庭作业问题 - 他们被要求构建一个算法......
  • 是否允许将 String 转换为 CharArray?因为那时您可以遍历所有字符并检查它是否在数组中。还是不允许使用任何 String.function?
  • 这是在java中,我不想使用字符串内置函数
  • 尾随 *s 从输出中去哪里?

标签: java string character


【解决方案1】:

我会说使用内置的方式从字符串中读取一个字符数组和一个 foreach 循环来删除包含的字符。

对于 c#,它看起来像这样:

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

当然你也可以使用索引和 str.Remove() 来避免空格...

-编辑对不起,我刚刚读到您不允许使用内置函数-但是从字符串作为数组读取是没有功能的-每个字符串都作为字符数组保存在内存中-所以这应该没问题,只需要更改删除字符的方式:

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++;
   }
}

尚未验证...但我希望它有效:)

【讨论】:

  • 嘿,Lorenz,谢谢,但我不想使用字符串内置函数,你说使用 Replace() 和 Trim()。这不是我的解决方案...
  • 看上面...编辑了一种没有内置函数的方法,希望它有效;)
  • 再次编辑,所以应该没有空格 - 感谢 Daniel!
【解决方案2】:
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();
}

【讨论】:

  • 感谢 Emil,但我不想使用字符串内置函数。例如您在上述代码中使用的 (toCharArray()) 。谢谢好榜样
【解决方案3】:

这是完整的示例。这不是您可以获得的最佳效果,但是由于您不能使用专门针对您的问题而设计的功能,因此应该可以正常工作:

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());
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-29
    • 1970-01-01
    相关资源
    最近更新 更多