Ho una stringa da dire
"Hello! world!"
Voglio fare un taglio o una rimozione per eliminare il! fuori dal mondo ma non fuori Ciao.
Ho una stringa da dire
"Hello! world!"
Voglio fare un taglio o una rimozione per eliminare il! fuori dal mondo ma non fuori Ciao.
Risposte:
"Hello! world!".TrimEnd('!');
MODIFICARE:
Quello che ho notato in questo tipo di domande che quasi tutti suggeriscono di rimuovere l'ultimo carattere di una determinata stringa. Ma questo non soddisfa la definizione del metodo Trim.
Taglia: rimuove tutte le occorrenze di caratteri di spazi bianchi dall'inizio e dalla fine di questa istanza.
In base a questa definizione, rimuovere solo l'ultimo carattere dalla stringa è una soluzione errata.
Quindi se vogliamo "Tagliare l'ultimo carattere dalla stringa" dovremmo fare qualcosa del genere
Esempio come metodo di estensione:
public static class MyExtensions
{
public static string TrimLastCharacter(this String str)
{
if(String.IsNullOrEmpty(str)){
return str;
} else {
return str.TrimEnd(str[str.Length - 1]);
}
}
}
Nota se si desidera rimuovere tutti i caratteri dello stesso valore, ad es. (!!!!) il metodo sopra rimuove tutte le esistenze di '!' dalla fine della stringa, ma se vuoi rimuovere solo l'ultimo carattere dovresti usare questo:
else { return str.Remove(str.Length - 1); }
String withoutLast = yourString.Substring(0,(yourString.Length - 1));
if (yourString.Length > 1)
withoutLast = yourString.Substring(0, yourString.Length - 1);
o
if (yourString.Length > 1)
withoutLast = yourString.TrimEnd().Substring(0, yourString.Length - 1);
... nel caso in cui si desideri rimuovere un carattere non bianco dalla fine.
TrimEnd()metodo e se ci fosse potrebbe far Substring(..)fallire la chiamata successiva su stringhe brevi.
string s1 = "Hello! world!";
string s2 = s1.Trim('!');
Prova questo:
return( (str).Remove(str.Length-1) );
potresti anche usare questo:
public static class Extensions
{
public static string RemovePrefix(this string o, string prefix)
{
if (prefix == null) return o;
return !o.StartsWith(prefix) ? o : o.Remove(0, prefix.Length);
}
public static string RemoveSuffix(this string o, string suffix)
{
if(suffix == null) return o;
return !o.EndsWith(suffix) ? o : o.Remove(o.Length - suffix.Length, suffix.Length);
}
}
Versione leggermente modificata di @Damian Leszczyński - Vash che farà in modo che venga rimosso solo un personaggio specifico.
public static class StringExtensions
{
public static string TrimLastCharacter(this string str, char character)
{
if (string.IsNullOrEmpty(str) || str[str.Length - 1] != character)
{
return str;
}
return str.Substring(0, str.Length - 1);
}
}
Ho preso il percorso di scrivere un'estensione usando TrimEnd solo perché lo stavo già usando in linea e ne ero contento ... cioè:
static class Extensions
{
public static string RemoveLastChars(this String text, string suffix)
{
char[] trailingChars = suffix.ToCharArray();
if (suffix == null) return text;
return text.TrimEnd(trailingChars);
}
}
Assicurati di includere lo spazio dei nomi nelle tue classi usando la classe statica; P e l'utilizzo è:
string _ManagedLocationsOLAP = string.Empty;
_ManagedLocationsOLAP = _validManagedLocationIDs.RemoveLastChars(",");
Un esempio di classe di estensione per semplificare questo: -
internal static class String
{
public static string TrimEndsCharacter(this string target, char character) => target?.TrimLeadingCharacter(character).TrimTrailingCharacter(character);
public static string TrimLeadingCharacter(this string target, char character) => Match(target?.Substring(0, 1), character) ? target.Remove(0,1) : target;
public static string TrimTrailingCharacter(this string target, char character) => Match(target?.Substring(target.Length - 1, 1), character) ? target.Substring(0, target.Length - 1) : target;
private static bool Match(string value, char character) => !string.IsNullOrEmpty(value) && value[0] == character;
}
uso
"!Something!".TrimLeadingCharacter('X'); // Result '!Something!' (No Change)
"!Something!".TrimTrailingCharacter('S'); // Result '!Something!' (No Change)
"!Something!".TrimEndsCharacter('g'); // Result '!Something!' (No Change)
"!Something!".TrimLeadingCharacter('!'); // Result 'Something!' (1st Character removed)
"!Something!".TrimTrailingCharacter('!'); // Result '!Something' (Last Character removed)
"!Something!".TrimEndsCharacter('!'); // Result 'Something' (End Characters removed)
"!!Something!!".TrimLeadingCharacter('!'); // Result '!Something!!' (Only 1st instance removed)
"!!Something!!".TrimTrailingCharacter('!'); // Result '!!Something!' (Only Last instance removed)
"!!Something!!".TrimEndsCharacter('!'); // Result '!Something!' (Only End instances removed)
Se vuoi rimuovere il '!' carattere di un'espressione specifica ("mondo" nel tuo caso), quindi puoi usare questa espressione regolare
string input = "Hello! world!";
string output = Regex.Replace(input, "(world)!", "$1", RegexOptions.Multiline | RegexOptions.Singleline);
// result: "Hello! world"
il carattere speciale $ 1 contiene tutte le espressioni "mondo" corrispondenti e viene utilizzato per sostituire l'originale "mondo!" espressione