Substring, Replace, finding the next word etc in C#
This is seems to be tricky and I stumble on the last hurdle. I tried different logics, but din quite work. So I dont provide my code. But I'll post what output I need. It's a matter of logic I guess though i'm sure i do need to certainly know methods more than .Substring()
and .Replace()
.
Input is a string. and the output is an altered form of the input string. Here's what i want.
input: "happy" output: "happy"
input: "he is a cheat" output: "he is a cheat"
input: "he c h e a t e d me" output: "he c h e a...t e d me"
input: "this is my p a r r o t" output: "this is my p a...r r o t"
That's at times few particular words in the string in my program can be separated by a space(parrot, cheated in the above examples). What I want to happen is
.Replace("a ", "a...");
Whenever there is "a" in the words split with space(p a r r o t, c h e a t e d), I want three dots to follow "a". I can do that. What compounds my problem is "a" is also a common word in english use to denote "one" (a mango, an apple etc). I dont want the program to add three dots after such "a's". An example below.
input: "m a n g o i开发者_开发问答s a fruit" output: "m a...n g o is a fruit"
How can this be done? Any logic would do if it gives the output as I desire. I hope I could make my requirement clear. If I miss anything please ask. Thanks
This will work in the cases you mentioned...
string input = "once a c h e a t e r always a cheater";
string output = Regex.Replace(input, @"(?<=\b\w )a (?=\w\b)", "a...");
Console.WriteLine(output); // once a c h e a...t e r always a cheater
It checks that the surrounding "words" are a single letter.
I am not sure but you can try, find substring 'a',fetch next string and if after occurance of a thr is a string which is like character space character space then replace that a with a...
精彩评论