1

次のような文字列があるとします: ma, 100or, ma, word, or even ma. , *+etc.

句読点 (ピリオド、カンマ、コロン、セミコロン) または空白ではない最初の文字のインデックスの後の位置を見つけるにはどうすればよいですか。*したがって、上記の最後の例では、開始インデックス (ゼロベース) として 1 を渡したときの位置を取得したいと考えています。

4

3 に答える 3

4

一致させたい文字の配列を作成し、String.IndexOfAnyを呼び出します。

例えば:

const string GoodCharsStr =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxy";
readonly char[] GoodChars = GoodCharsStr.ToCharArray();

string search = "ma, 100";
int position = search.IndexOfAny(GoodChars, 1);
if (position == -1)
{
    // not found
}
char foundChar = search[position];
于 2013-08-02T18:17:21.753 に答える
3

特殊文字とは何かを正確に定義する必要があります。

連続していないセット (ASCII の順序に従って、http://www.asciitable.com/を参照) の場合は、新しい許可された文字セットを定義し、そのセットに対してチェックする必要があります。

このようなものが動作するはずです:

public const string allowed = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.,";

public int RetrieveIndex(string input, int startIndex)
{
    for (var x = startIndex; x < input.length; x++)
    {
        if (allowed.IndexOf(input[x])==-1)
        {
            return x;
        }
     }

    return -1;
}

ただし、ASCII 標準で定義されている連続したセットの場合:

許容範囲または特別と見なされる範囲を特定し、文字を整数に変換して範囲内にあるかどうかを確認することで、それを確認します。これは、 への呼び出しよりも高速であることが証明されallowed.IndexOf(...)ます。

于 2013-08-02T17:58:16.817 に答える
1

このような方法を使用できます

public static int GetFirstNonPunctuationCharIndex(string input, int startIndex, char[] punctuation)
{
    //Move the startIndex forward one because we ignore the index user set
    startIndex = startIndex + 1 < input.Length ? startIndex + 1 : input.Length;                 

    for (int i = startIndex  ; i < input.Length; i++)
    {
        if (!punctuation.Contains(input[i]) && !Char.IsWhiteSpace(input[i]))
        {
             return i;
        }
    }

    return -1;
}

文字列、開始インデックス、および句読点と見なす文字の配列を渡すことで呼び出します。

string myString = @"ma. , *+";
char[] puncArray = new char[4] { '.', ',', ';', ':' };
int index = GetFirstNonPunctuationCharIndex(myString, 1, puncArray)

通常はChar.IsPunctuationメソッドを使用しますが、明らかに句読点と見なさ*れるため、上記のように独自にロールする必要があります。

于 2013-08-02T18:01:18.687 に答える