How to get the first word from a string in C#

4 Answers

0 votes
using System;

class Program
{
    static void Main() {
        string s = "c# javascript php c c++ python vb.net"; 
        
        Console.Write(s.Substring(0, s.IndexOf(" ")));
    }
}



/*
run:

c#

*/

 



answered Sep 8, 2019 by avibootz
0 votes
using System;

class Program
{
    static void Main() {
        string s = "c# javascript php c c++ python vb.net"; 
        
        string first_word = s.IndexOf(" ") > -1 ? s.Substring(0, s.IndexOf(" ")) : s;
        
        Console.Write(first_word);
    }
}




/*
run:

c#

*/

 



answered Sep 8, 2019 by avibootz
edited Sep 8, 2019 by avibootz
0 votes
using System;
using System.Linq;

class Program
{
    static void Main() {
        string s = "c# javascript php c c++ python vb.net"; 
        
        string first_word = s.Split(' ').First();
        
        Console.Write(first_word);
    }
}




/*
run:

c#

*/

 



answered Sep 8, 2019 by avibootz
0 votes
using System;

class Program
{
    static void Main() {
        string s = "c# javascript php c c++ python vb.net"; 
        
        string first_word = s.Split(' ')[0];
        
        Console.Write(first_word);
    }
}




/*
run:

c#

*/

 



answered Sep 8, 2019 by avibootz

Related questions

1 answer 122 views
1 answer 100 views
1 answer 141 views
3 answers 256 views
4 answers 322 views
...