この文字列をどのようにトリミングすればよいか困っています。最後の「/」以降をすべて削除したいのですが、「/」が複数あります。
例:
から:http://stackoverflow.com/questions/ask/randomcrap.html
に:http://stackoverflow.com/questions/ask/
文字列のトリミングは、組み込みの文字列ユーティリティの多くを使用して行うことができます。
最初LastIndexOf
に文字列に「/」文字が必要であり、次に文字列のインデックス(文字列の先頭) から文字Substring
のインデックスまでメソッドを使用します。スラッシュを含めたい場合は、もう 1 つインデックスを追加する必要があります。0
/
/
static string getToLastSlash(string inString)
{
var index = inString.LastIndexOf('/');
if (index == -1)
throw new Exception("/ not found in string");
return inString.Substring(0, index + 1);
}
このLastIndexOf()
メソッドは、指定された特定の文字または文字列の最後のインデックスを返します。LastIndexOf()
メソッドが一致を評価しない場合、結果は になります-1
。一致しない可能性があるという事実を考慮して、最初に一致結果が であるかどうかを確認する必要があり-1
ます。上記のメソッドでは単に例外をスローしますが、アプリケーションにはこの状況を処理するための代替メソッドがある場合があります。
一致がそれより大きい場合、-1
一致が見つかったと見なすことができます。一致が見つかった場合は、メソッドを使用して、位置からSubstring()
始まる文字列内のすべての文字を解析できます。0
index+1
end( ) anchorで正規表現Replaceを使用します。$
var res = Regex.Replace(input,
@"[^/]+$", // match all the non-slashes anchored to the end of input
""); // replace any matched characters with nothing
// and make sure to use "res"
このようなタスクには正規表現を使用することを好みます。これは、より単純であり、「無料で」余分な条件付きガードを回避できるためです。ただし、使用されるアプローチの仕組みを必ず理解してください。
組み合わせstring.Substring
てstring.LastIndexOf
、トリックを行う必要があります。
最も簡単な方法はおそらく
string myURL = "http://stackoverflow.com/questions/ask/randomcrap.html";
string str = myURL.Substring(0, myURL.LastIndexOf('/'));
Console.WriteLine(str);
どちらが出力されますか
http://stackoverflow.com/questions/ask
最後の「/」文字を見つけたい場合は、String LastIndexOfメソッドを使用してください。
String text = @"http://stackoverflow.com/questions/ask/randomcrap.html";
String result = text;
int index = text.LastIndexOf('/'); // <- last '/' if any
if (index >= 0) // <- if there's '/' within the string, trim it
result = text.Substring(0, index + 1);
...
Console.Out.Write(result); // <- http://stackoverflow.com/questions/ask/
Split
char'/'
を a に変換しList<string>
、最後の項目を削除して、最後に次を使用してパーツを再結合することができますstring.Join
var url = "http://stackoverflow.com/questions/ask/randomcrap.html";
var b = url.Replace("http://", "").Split('/').ToList(); //replace "html://" to avoid problems with the split
b.RemoveAt(b.Count-1); //last index
var result = "http://" + string.Join("/", b) + "/";
result
に等しい"http://stackoverflow.com/questions/ask/"
これにより、必要な部分を削除できます。
も使用できることを忘れないでくださいb.RemoveRange(int index, int count)
。
このようにLastIndexOfを使用できます
string str = "http://stackoverflow.com/questions/ask/randomcrap.html";
string final = RemoveAfterLastChar(str, '/');
public string RemoveAfterLastChar(string input, char c)
{
var index = input.LastIndexOf(c);
if (index != -1)
return input.Substring(0, index + 1);
else
return input;
}
または、形式が常に例と同じになる場合は、Path.GetDirectoryNameを使用できます。
input = Path.GetDirectoryName(input);