と仮定、私は次の文字列をしましたシングルQoute交換
Hello, how are you? your name what you want
一重引用符内のコンマは置き換えられず、アウトのみが出力されます。それの理想。
と仮定、私は次の文字列をしましたシングルQoute交換
Hello, how are you? your name what you want
一重引用符内のコンマは置き換えられず、アウトのみが出力されます。それの理想。
です。一重引用符の中にコンマを分割しないようにしたいですか?
私は、次の拡張方法を思い付いた:
static class Extention
{
public static string[] SplitOutsideSingleQuotes(this string text, char splittingChar)
{
bool insideSingleQuotes = false;
List<string> parts = new List<string>() { "" }; // The part in which the text is split
foreach (char ch in text)
{
if (ch == '\'') // Determine whenever we enter or exit a single quote
{
insideSingleQuotes = !insideSingleQuotes;
continue; // The single quote shall not be in the final output. Therefore continue
}
if (ch == splittingChar && !insideSingleQuotes)
{
parts.Add(""); // There is a 'splittingChar'! Create new part
}
else
parts[parts.Count - 1] += ch; // Add the current char to the latest part
}
return parts.ToArray();
}
}
今、あなたの出力用として。あなたが一緒に配列内の文字列を入れてstring.Join(string, string[])
を使用することができます。
string.Join("", word); // This puts all the strings together with "" (excactly nothing) between them
これはになります:こんにちは
、どのようにしていますか?あなたの名前あなたは
何をしたいあなたは、正規表現を使ってこれを実現することができます
private const string SPLIT_FORMAT = "{0}(?=(?:[^']*'[^']*')*[^']*$)";
public static string SplitOutsideSingleQuotes(this string text, char splittingChar)
{
string[] parts = Regex.Split(text, String.Format(SPLIT_FORMAT, splittingChar), RegexOptions.None);
for (int i = 0; i < parts.Length; i++)
{
parts[i] = parts[i].Replace("'", "");
}
return String.Join("", parts);
}
コードは、単一引用符のsplittingChar
外側に分割するために式を使用しています。次に、結果の文字列配列の各一重引用符が置き換えられます。最後に、部品を一緒に結合します。
返事をありがとう。しかし、私は答えとしてマークしたり、投票したりすることができません。努力のためにもう一度ありがとう。 –
string str = "'Hello, how are you?', 'your name', what you want";
string str1=str.Replace("',","");
str1 = str1.Replace("'", "");
Console.WriteLine(str1);
Console.ReadLine();
出力: こんにちは、どうですか?あなたの名前あなたが欲しいもの
注:私が間違っている場合、あなたが望む出力を教えてください。私はあなたが望むように得る方法を教えてくれるでしょう。
保存したいコンマの一重引用符を検出するためにスタックを使用したい場合があります。ここにコードスニペットがあります:
static void Main(string[] args)
{
string str = "'Hello, how are you?', 'your name', what you want";
string outputString = String.Empty;
Stack<char> runningStack = new Stack<char>();
foreach (var currentCharacter in str)
{
if (currentCharacter == '\'')
{
if (runningStack.Count > 0)
{
//this is closing single quote. so empty the stack
runningStack.Clear();
}
else
{
runningStack.Push(currentCharacter);
}
}
else
{
if (currentCharacter == ',')
{
if (runningStack.Count > 0)
{//there was an opening single quote before it. So preserve it.
outputString += currentCharacter;
}
}
else
{
outputString += currentCharacter;
}
}
}
}
最初のものあなたのステートメントストリングstr = ""こんにちは、どうですか? "、"あなたの名前 "、あなたは何ですか?間違っている。それは決してコンパイルされません。最初に修正してください。 –
出力を表示するには、これをしないでください。 'string str ="こんにちは、お元気ですか? " – MasterXD
どうして最初のカンマが結果の文字列に残っていますか?それはタイプミスなのでしょうか? – user3185569