4

(文字列内の各文字を明示的にループする必要なしに)高速な方法があり、それを削除または保持しますか?Visual FoxProには、それをうまく実行する関数CHRTRAN()があります。1:1の文字置換ですが、代替位置に文字がない場合は、最終的な文字列から削除されます。元

CHRTRAN( "これはテストになります"、 "it"、 "X")

戻ります

「ThXswXllbeaes」

元の「i」が「X」に変換され、小文字の「t」が削除されていることに注意してください。

同様の目的で置換を検討しましたが、何も置換しないオプションは見つかりませんでした。

さまざまなタイプの入力制限があるデータの複数のオリジンを検証するために、いくつかの汎用ルーチンを作成しようとしています。一部のデータは外部ソースからのものである可能性があるため、テストする必要があるのはテキストボックスエントリの検証だけではありません。

ありがとう

4

6 に答える 6

9

必要なのは、String.Replace()を数回呼び出すことだけです。

string s = "This will be a test";
s = s.Replace("i", "X");
s = s.Replace("t", "");

Replace()は新しい文字列を返すことに注意してください。文字列自体は変更されません。

于 2009-05-11T17:56:44.493 に答える
5

これはあなたが望むものですか?

"This will be a test".Replace("i", "X").Replace("t", String.Empty)

これは関数の簡単な実装です-文字列に含まれていて非常に乱雑なCHRTRAN場合は機能しません。\0ループを使用してより良いものを作成することもできますが、私はLINQを使用してそれを試してみたかっただけです。

public static String ChrTran(String input, String source, String destination)
{
    return source.Aggregate(
        input,
        (current, symbol) => current.Replace(
            symbol,
            destination.ElementAtOrDefault(source.IndexOf(symbol))),
        preResult => preResult.Replace("\0", String.Empty));
}

そして、あなたはそれを使うことができます。

// Returns "ThXs wXll be a es"
String output = ChrTran("This will be a test", "it", "X");

クリーンなソリューションを提供するためだけに、LINQがなくても同じで、\0ケースでもStringBuilder機能します。もちろん、入力を変更することはありませんが、使用しているため、ほぼ適切です。

public static String ChrTran(String input, String source, String destination)
{
    StringBuilder result = new StringBuilder(input);

    Int32 minLength = Math.Min(source.Length, destination.Length);

    for (Int32 i = 0; i < minLength; i++)
    {
        result.Replace(source[i], destination[i]);
    }

    for (Int32 i = minLength; i < searchPattern.Length; i++)
    {
        result.Replace(source[i].ToString(), String.Empty);
    }

    return result.ToString();
}

ヌル参照処理がありません。

tvanfossonのソリューションに触発されて、私はLINQにセカンドショットを与えました。

public static String ChrTran(String input, String source, String destination)
{
    return new String(input.
        Where(symbol =>
            !source.Contains(symbol) ||
            source.IndexOf(symbol) < destination.Length).
        Select(symbol =>
            source.Contains(symbol)
                ? destination[source.IndexOf(symbol)]
                : symbol).
        ToArray());
}
于 2009-05-11T17:59:11.023 に答える
5

これが私の最終的な機能であり、期待どおりに完全に機能します。

public static String ChrTran(String ToBeCleaned, 
                             String ChangeThese, 
                             String IntoThese)
{
   String CurRepl = String.Empty;
   for (int lnI = 0; lnI < ChangeThese.Length; lnI++)
   {
      if (lnI < IntoThese.Length)
         CurRepl = IntoThese.Substring(lnI, 1);
      else
         CurRepl = String.Empty;

      ToBeCleaned = ToBeCleaned.Replace(ChangeThese.Substring(lnI, 1), CurRepl);
   }
   return ToBeCleaned;
}
于 2009-05-13T01:47:51.023 に答える
4

これは、LINQを使用すると問題が複雑になりすぎると思う場合です。これは単純で要点です。

private static string Translate(string input, string from, string to)
{
    StringBuilder sb = new StringBuilder();
    foreach (char ch in input)
    {
        int i = from.IndexOf(ch);
        if (from.IndexOf(ch) < 0)
        {
            sb.Append(ch);
        }
        else
        {
            if (i >= 0 && i < to.Length)
            {
                sb.Append(to[i]);
            }
        }
    }
    return sb.ToString();
}
于 2009-05-11T19:38:26.387 に答える
3

「何も置き換えない」には、空の文字列に置き換えるだけです。これはあなたに与えるでしょう:

String str = "This will be a test";
str = str.Replace("i", "X");
str = str.Replace("t","");
于 2009-05-11T17:59:11.680 に答える
3

文字列拡張子としてのより一般的なバージョン。他の文字列と同様に、文字列はC#で不変であるため、これはその場で変換を行いませんが、代わりに、指定された置換を含む新しい文字列を返します。

public static class StringExtensions
{
    public static string Translate( this string source, string from, string to )
    {
        if (string.IsNullOrEmpty( source ) || string.IsNullOrEmpty( from ))
        {
            return source;
        }

        return string.Join( "", source.ToCharArray()
                                   .Select( c => Translate( c, from, to ) )
                                   .Where( c => c != null )
                                   .ToArray() );
    }

    private static string Translate( char c, string from, string to )
    {
        int i = from != null ? from.IndexOf( c ) : -1;
        if (i >= 0)
        {
            return (to != null && to.Length > i)
                      ? to[i].ToString()
                      : null;
        }
        else
        {
            return c.ToString();
        }
    }
}
于 2009-05-11T18:20:51.473 に答える