简体   繁体   中英

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";

you could use Split(char c) that will give you back an array of sub string s 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];

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);
}

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|_");

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];
string src = "A~B~C~D";
string[] letters = src.Split('~');

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

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

\\w matches a single word ie AZ or az or _ or a digit

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

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);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM