I have a string, it may looks like this:
asjlfkajs alsdkfja s asldfkjas @abc dfasldkfj asldkfj las @nveweb dfasdlf asldfj.
I want to change any word started with @, to %@ %. for example,
@abc change to %@abc%
Can anyone show me an exmaple? I really have no idea about it, how to detect any word starting with @ and add % in the beginning and end of every such word?
Perhaps simply:
str = string.Join(" ", str.Split()
.Select(w => w.StartsWith("@") ? "%" + w + "%" : w));
You need to add using system.Linq;
at the top since the argument to String.Join
is a LINQ query. String.Split
without argument splits by white-spaces which includes spaces, new-lines and tabs. At the end the Join
will concat all with a space which means that you don't retain possible new-line or tab-characters.
However, the query itself does following, str.Split()
returns all "words". Enumerable.Select
projects a string which is either the orginal string (if the word doesn't start with @
) or a new string which is wrapped by %
.
Update if you want to retain the separator if they are at the beginning or at the end of words and don't want them to be wrapped also as in:
@abc. --> wrong: %@abc.% correct: %@abc%.
The you could use following method:
static readonly HashSet<char> WordSeparators = new HashSet<char> { ',', '.', '!', '?', ';', ':', ' ', '-', '/', '\\', '[', ']', '(', ')', '<', '>', '"', '\'' };
static string WrapWithIfStartsWith(string input, string startsWith, string wrap, StringComparison comparison = StringComparison.CurrentCulture)
{
if (string.IsNullOrEmpty(input) || !input.StartsWith(startsWith, comparison))
return input;
else if(input.Length == 1)
return string.Format("{1}{0}{1}", input, wrap);
char first = input.First();
char last = input.Last();
bool firstIsSeparator = WordSeparators.Contains(first);
bool lastIsSeparator = WordSeparators.Contains(last);
if (firstIsSeparator && lastIsSeparator)
return string.Format("{0}{1}{2}{1}{3}",
first, wrap, input.Substring(1, input.Length - 2), last);
else if (firstIsSeparator && !lastIsSeparator)
return string.Format("{0}{1}{2}{1}",
first, wrap, input.Substring(1));
else if (!firstIsSeparator && lastIsSeparator)
return string.Format("{0}{1}{0}{2}",
wrap, input.Remove(input.Length - 1), last);
else
return string.Format("{1}{0}{1}", input, wrap);
}
Now it's simple as:
string str = "blabalbal blabal @abc.";
str = string.Join(" ", str.Split().Select(w => WrapWithIfStartsWith(w,"@","%")));
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments