web-dev-qa-db-fra.com

Extrait seulement la plupart des n lettres d'une chaîne

Comment puis-je extraire une sous-chaîne composée des six lettres les plus à droite d'une autre chaîne?

Ex: ma chaîne est "PER 343573". Maintenant, je veux extraire uniquement "343573".

Comment puis-je faire ceci?

94
Shyju
string SubString = MyString.Substring(MyString.Length-6);
137
Vilx-

Ecrivez une méthode d'extension pour exprimer la fonction Right(n);. La fonction doit traiter les chaînes nulles ou vides renvoyant une chaîne vide, les chaînes inférieures à la longueur maximale renvoyant la chaîne d'origine et les chaînes supérieures à la longueur maximale renvoyant la longueur maximale des caractères les plus à droite.

public static string Right(this string sValue, int iMaxLength)
{
  //Check if the value is valid
  if (string.IsNullOrEmpty(sValue))
  {
    //Set valid empty string as string could be null
    sValue = string.Empty;
  }
  else if (sValue.Length > iMaxLength)
  {
    //Make the string no longer than the max length
    sValue = sValue.Substring(sValue.Length - iMaxLength, iMaxLength);
  }

  //Return the string
  return sValue;
}
64
stevehipwell

Probablement plus agréable d'utiliser une méthode d'extension:

public static class StringExtensions
{
    public static string Right(this string str, int length)
    {
        return str.Substring(str.Length - length, length);
    }
}

Usage

string myStr = "ABCDEPER 343573";
string subStr = myStr.Right(6);
37
James
using System;

public static class DataTypeExtensions
{
    #region Methods

    public static string Left(this string str, int length)
    {
        str = (str ?? string.Empty);
        return str.Substring(0, Math.Min(length, str.Length));
    }

    public static string Right(this string str, int length)
    {
        str = (str ?? string.Empty);
        return (str.Length >= length)
            ? str.Substring(str.Length - length, length)
            : str;
    }

    #endregion
}

Si une erreur ne devrait pas se produire, la valeur null est renvoyée sous forme de chaîne vide, ainsi que les valeurs tronquées ou de base. Utilisez-le comme "testx" .Left (4) ou str.Right (12);

25
Jeff Crawford

MSDN

String mystr = "PER 343573";
String number = mystr.Substring(mystr.Length-6);

EDIT: trop lent ...

13
RvdK

si vous n'êtes pas sûr de la longueur de votre chaîne, mais que vous comptez le nombre de mots (toujours 2 mots dans ce cas, comme 'xxx yyyyyy'), vous feriez mieux d'utiliser split. 

string Result = "PER 343573".Split(" ")[1];

cela retourne toujours le deuxième mot de votre chaîne.

8
Mahdi Tahsildari

Ce n'est pas exactement ce que vous demandez, mais si vous regardez juste l'exemple, il apparaît que vous recherchez la section numérique de la chaîne.

Si c'est toujours le cas, une bonne méthode consiste à utiliser une expression régulière.

var regex= new Regex("\n+");
string numberString = regex.Match(page).Value;
6
chills42

Devinez selon vos besoins, mais l'expression régulière suivante ne donnera que sur 6 caractères alphanumériques avant la fin de la chaîne et aucune correspondance sinon.

string result = Regex.Match("PER 343573", @"[a-zA-Z\d]{6}$").Value;
5
Wade

Utilisez ceci:

String text = "PER 343573";
String numbers = text;
if (text.Length > 6)
{
    numbers = text.Substring(text.Length - 6);
}
5
cjk

Comme vous utilisez .NET, qui compile tous les éléments dans MSIL , il suffit de référencer Microsoft.VisualBasic et utilise la méthode intégrée Strings.Right de Microsoft:

using Microsoft.VisualBasic;
...
string input = "PER 343573";
string output = Strings.Right(input, 6);

Pas besoin de créer une méthode d'extension personnalisée ou un autre travail. Le résultat est obtenu avec une référence et une simple ligne de code.

Pour plus d’informations à ce sujet, l’utilisation de méthodes Visual Basic avec C # a été documentée ailleurs . Personnellement, je suis tombé dessus en essayant d’analyser un fichier et j’ai trouvé ce fil SO / en utilisant la classe Microsoft.VisualBasic.FileIO.TextFieldParser extrêmement utile pour l’analyse de fichiers .csv.

4
Aaron Thomas

Utilisez ceci:

string mystr = "PER 343573"; int number = Convert.ToInt32(mystr.Replace("PER ",""));

3
Brandao

C’est la méthode que j’utilise: j’aime garder les choses simples.

private string TakeLast(string input, int num)
{
    if (num > input.Length)
    {
        num = input.Length;
    }
    return input.Substring(input.Length - num);
}
2

Méthodes Null Safe:

Chaînes plus courtes que la longueur maximale renvoyant la chaîne d'origine

Méthode d'extension droite de chaîne

public static string Right(this string input, int count) =>
    String.Join("", (input + "").ToCharArray().Reverse().Take(count).Reverse());

Méthode d'extension de chaîne gauche

public static string Left(this string input, int count) =>
    String.Join("", (input + "").ToCharArray().Take(count));
2
desmati

Une autre solution à ne pas mentionner

S.Substring(S.Length < 6 ? 0 : S.Length - 6)
1
FLICKER
var str = "PER 343573";
var right6 = string.IsNullOrWhiteSpace(str) ? string.Empty 
             : str.Length < 6 ? str 
             : str.Substring(str.Length - 6); // "343573"
// alternative
var alt_right6 = new string(str.Reverse().Take(6).Reverse().ToArray()); // "343573"

cela prend en charge n'importe quel nombre de caractères dans la variable str. le code alternatif ne supporte pas la chaîne null. et le premier est plus rapide et le second est plus compact.

je préfère le second si je connais la str contenant une chaîne courte. si c'est long, le premier convient mieux.

par exemple.

var str = "";
var right6 = string.IsNullOrWhiteSpace(str) ? string.Empty 
             : str.Length < 6 ? str 
             : str.Substring(str.Length - 6); // ""
// alternative
var alt_right6 = new string(str.Reverse().Take(6).Reverse().ToArray()); // ""

ou

var str = "123";
var right6 = string.IsNullOrWhiteSpace(str) ? string.Empty 
             : str.Length < 6 ? str 
             : str.Substring(str.Length - 6); // "123"
// alternative
var alt_right6 = new string(str.Reverse().Take(6).Reverse().ToArray()); // "123"
1
Supawat Pusavanno

Juste une pensée:

public static string Right(this string @this, int length) {
    return @this.Substring(Math.Max(@this.Length - length, 0));
}
1
Hamid Sadeghian

Voici la solution que j'utilise .... Il vérifie que la longueur de la chaîne d'entrée n'est pas inférieure à la longueur demandée. Les solutions que je vois affichées ci-dessus n'en tiennent malheureusement pas compte, ce qui peut entraîner des accidents.

    /// <summary>
    /// Gets the last x-<paramref name="amount"/> of characters from the given string.
    /// If the given string's length is smaller than the requested <see cref="amount"/> the full string is returned.
    /// If the given <paramref name="amount"/> is negative, an empty string will be returned.
    /// </summary>
    /// <param name="string">The string from which to extract the last x-<paramref name="amount"/> of characters.</param>
    /// <param name="amount">The amount of characters to return.</param>
    /// <returns>The last x-<paramref name="amount"/> of characters from the given string.</returns>
    public static string GetLast(this string @string, int amount)
    {
        if (@string == null) {
            return @string;
        }

        if (amount < 0) {
            return String.Empty;
        }

        if (amount >= @string.Length) {
            return @string;
        } else {
            return @string.Substring(@string.Length - amount);
        }
    }
1
Yves Schelpe

Sans recourir au convertisseur de bits et au décalage de bits (il faut être sûr de bien coder).

string myString = "123456789123456789";

if (myString > 6)
{

        char[] cString = myString.ToCharArray();
        Array.Reverse(myString);
        Array.Resize(ref myString, 6);
        Array.Reverse(myString);
        string val = new string(myString);
}
0
user86157

J'utilise le Min pour éviter les situations négatives et gère également les chaînes vides

// <summary>
    /// Returns a string containing a specified number of characters from the right side of a string.
    /// </summary>
    public static string Right(this string value, int length)
    {
        string result = value;
        if (value != null)
            result = value.Substring(0, Math.Min(value.Length, length));
        return result;
    }
0
RitchieD
using Microsoft.visualBasic;

 public class test{
  public void main(){
   string randomString = "Random Word";
   print (Strings.right(randomString,4));
  }
 }

la sortie est "Word"

0
Steve Short
//s - your string
//n - maximum number of right characters to take at the end of string
(new Regex("^.*?(.{1,n})$")).Replace(s,"$1")
0
vldmrrr