Moses Zaodi
Moses Zaodi

Reputation: 39

how to get multiple occurrences in a string with substring?

I want to get all the game names from a string to a list, How can I do that without getting the same name again?

I have tried to use for loop like in the example below my error was that I got the same name again then I try to remove the keyword name so it will just skip to the next one but the keyword is shown multiple times and I cannot remove it

I have tried:

List <string> list = new List <string>();
int GamesAmount = 2;
string games = "Name: game1, StatusName Name: game2,";
for(int i = 0;i < GamesAmount; i++) 
{
    string currentGame = games.Substring("Name: ", ",");
    list.Add(currentGame);
    games = games.Remove(0, IndexOf("name") + 4);
}

at the end I want

list[game1, game2];

Upvotes: 2

Views: 1646

Answers (5)

kara
kara

Reputation: 3455

If you got a clean list the upper answers will work just fine. In addition I'd suggest to use a Regex to make it possible to use more complex patterns.

Example

// some crappy input string with upper and lower case and spaces only sometimes before the game name.
string inputString = "Name: game1, StatusName Name: game2, Bla bla Name: game1, Some more Text StatusName Name:game3"; ;

// Define a pattern (explaination on the bottom of this answer)
Regex gameName = new Regex("Name:[ ]?(?<GameName>[^,]*),", RegexOptions.IgnoreCase);

// Create a "list" which will contain the names in the end
HashSet<string> GameNames = new HashSet<string>();

// Loop through all substrings which match our pattern
foreach (Match m in gameName.Matches(inputString))
{
    string name = m.Groups["GameName"].Value;
    Console.WriteLine("Found: " + name); // what did we match?

    // add game to list if not contained
    GameNames.Add(name);
}

// Let's see what we got
Console.WriteLine("All Games: " + string.Join(", ", GameNames));

Output

Found: game1

Found: game2

Found: game1

All Games: game1, game2

Regex-Explaination:

Name:[ ]?(?<GameName>[^,]*),

Name:  // Has to start with this string
[ ]?   // A space-Character, which can occur 0 or 1 time ("?"). ([x]? would be a x 0 or 1 time)
(....) // is a group which can be accessed later
(?<name>) // is a group named "name" which can be accessed by name later
([^]+)    // is a group containing any character except comma. 1 to infinite times ("+")
,         // Match has to end with a comma.

Linq-Style

And if you like Linq and understood what you're doing, you can run queries on your matches:

    var instantList = new Regex("Name:[ ]?(?<GameName>[^,]*),", RegexOptions.IgnoreCase) // Create Regex
        .Matches(inputString) // Get Matches to our input
        .Cast<Match>() // Cast to Ienumerable<Match>
        .Select(s => s.Groups["GameName"].Value) // Select Gamename from Match
        .Distinct(); // remove doublicated

Upvotes: 2

Amir Molaei
Amir Molaei

Reputation: 3820

Assuming that all names start with colon plus space and end in ,:

            string games = "Name: game1, StatusName Name: game2,";
            var splittedText = games.Split(':');
            var currentGame = splittedText.Select(x => x.Length > 4 ? x.Substring(1, x.IndexOf(",") - 1) : "")
                .Where(y => y != "")
                .Distinct()
                .ToList();

Upvotes: 2

Prasad Telkikar
Prasad Telkikar

Reputation: 16049

You can split sentence into words and check condition where word contains game in it

Something like

    string games = "Name: game1, StatusName Name: game2,".Trim(','); //Remove last , from string
    List<string> g = games.Split(' ').Where(x => x.Contains("game")).ToList(); //Use of Linq
    foreach(var i in g)  //Iterate through list to print
        Console.WriteLine(i);

If game string is not constant in string then you can use below approach, it need just one extra for loop

    string games = "Name: game1, StatusName Name: game2,".Trim(',');
    List<string> str = games.Split(',').ToList();
    List<string>result = new List<string>();

    foreach(string i in str)
        result.Add(i.Split(' ').LastOrDefault());

    foreach(string r in result)
        Console.WriteLine(r);

POC : .Net Fiddle

Upvotes: 1

Fabio
Fabio

Reputation: 32455

Split by comma, then split by Name: and use HashSet<string> to return only unique game names

var gameNames =
    games.Split(',')
         .Select(game => game.Split('Name: ').LastOrDefault())
         .ToHashSet();

foreach (var gameName in gameNames)
{
    // use game name
}

Upvotes: 2

UsmanMirza
UsmanMirza

Reputation: 276

Before adding to List, i think you should simply check either that value already exists in List or not.

if(!list.Contains(currentGame))
    list.Add(currentGame);

if it is not in List then it should add to your List object.

Upvotes: 0

Related Questions