vb.net C#如何从字符串中获取单词

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19031118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 15:14:56  来源:igfitidea点击:

C# How to get Words From String

c#regexvb.netstringwords

提问by Krazii KiiD

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

回答by Eoin Campbell

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

你可以使用Split(char c)它会给你一个string由 ~ 符号分隔的 sub 数组。

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

显然,除非您事先知道字符串/单词的长度,否则您将无法随意将它们放入自己的变量中。但如果你知道它总是 4 个词,你就可以做

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

回答by Hossain Muctadir

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

回答by Amitkumar Arora

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

回答by e-on

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

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

回答by Jeroen van Langen

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

回答by gpmurthy

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

回答by Anirudha

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


\wmatches a single word i.e A-Z or a-z or _or a digit

\w匹配单个单词,即 AZ 或 az 或_或数字

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

+是一个量词,它匹配前面的字符 1 多次

回答by John Ryann

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