Krazii KiiD
Krazii KiiD

Reputation: 123

C# How to get Words From String

Hi guys i was trying a lot to retrieve some other strings from one main string.

string src = "A~B~C~D";

How can i retrieve separately the letters? Like:

string a = "A";
string b = "B";
string c = "C";
string d = "D";

Upvotes: 1

Views: 21325

Answers (8)

John Ryann
John Ryann

Reputation: 2393

I like to do it this way:

        List<char> c_list = new List<char>();
        string src = "A~B~C~D";
        char [] c = src.ToCharArray();
        foreach (char cc in c)
        {
            if (cc != '~')
                c_list.Add(cc);
        }

Upvotes: 1

gpmurthy
gpmurthy

Reputation: 2427

Consider...

string src = "A~B~C~D";
string[] srcList = src.Split(new char[] { '~' });
string a = srcList[0];
string b = srcList[1];
string c = srcList[2];
string d = srcList[3];

Upvotes: 2

Anirudha
Anirudha

Reputation: 32797

string words[]=Regex.Matches(input,@"\w+") 
                    .Cast<Match>()
                    .Select(x=>x.Value)
                    .ToArray();

\w matches a single word i.e A-Z or a-z or _ or a digit

+is a quantifier which matches preceding char 1 to many times

Upvotes: 1

Amitkumar Arora
Amitkumar Arora

Reputation: 149

Please try this

string src = "A~B~C~D"
//
// Split string on spaces.
// ... This will separate all the words.
//
string[] words = src .Split('~');
foreach (string word in words)
{
    Console.WriteLine(word);
}

Upvotes: 5

Eoin Campbell
Eoin Campbell

Reputation: 44268

you could use Split(char c) that will give you back an array of sub strings seperated by the ~ symbol.

string src = "A~B~C~D";

string [] splits = src.Split('~');

obviously though, unless you know the length of your string/words in advance you won't be able to arbitrarily put them in their own variables. but if you knew it was always 4 words, you could then do

string a = splits[0];
string b = splits[1];
string c = splits[2];
string d = splits[3];

Upvotes: 16

e-on
e-on

Reputation: 1605

string src = "A~B~C~D";
string[] letters = src.Split('~');

foreach (string s in letters)
{
    //loop through array here...
}

Upvotes: 3

Hossain Muctadir
Hossain Muctadir

Reputation: 3626

Try this one. It will split your string with all non-alphanumeric characters.

string s = "A~B~C~D";
string[] strings = Regex.Split(s, @"\W|_");

Upvotes: 6

Jeroen van Langen
Jeroen van Langen

Reputation: 22038

You can do:

string src = "A~B~C~D";

string[] strArray = src.Split('~');

string a = strArray[0];   
string b = strArray[1];   
string c = strArray[2];
string d = strArray[3];

Upvotes: 3

Related Questions