how to get the last items in a row - c#

I have string like Joe Doe Doe , owner business
and I need to take from this string last name, first name, father name and his position.
var str = orgRequ.ValueName.Replace(",", "").Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
string LastName = str.Length > 0 ? str[0] : "";
string Name = str.Length > 1 ? str[1] : "";
string FatherName = str.Length > 2 ? str[2] : "";
string Positions=string.Join(" ", str.Reverse().Take(str.Count() - 3).ToArray());
but ran into a problem that the final position is written as System.Linq.Enumerable + d__75`1 [System.Char] instead of the owner business. before insert into the database, i need again reverse Positions , how can this be cleaned using best practices

Because you are reversing the str in string Positions you get Business Owner instead of Owner Business.
So either you take str[3] + str[4] for a result of Owner Business:
string Positions = str[3] + " " + str[4];
Or with your code, you have to reverse the two words (attention, quick and dirty):
string Positions = string.Join(" ", str.Reverse().Take(str.Count() - 3).ToArray());
string output = "";
string[] splitStrings = Positions.Split(' ');
for (int i = splitStrings.Length - 1; i > -1; i--)
{
output = output + splitStrings[i] + " ";
}
Console.WriteLine("Result: " + output); //Owner Business

Related

Loop to get all probabilities of combining words

I have text that contains spaces.
I want all the possibilities. For example, merge a space and leave another.
For example, this is the first possibility:
the first word, then a space, the second word, then a space, then the third word.
The second possibility:
the first word, then without a space, then the second word, then a space, then the third word.
The third possibility:
the first word, then a space, then the second word, then without a space, then the third word ... etc..
I want to do this, but in a loop, especially if the number of words is more than five, six, or more.
static void Main(string[] args)
{
string test = "aaa bbb ccc";
var ch = test.Split(' ');
var t1 = ch[0] + " " + ch[1] + " " + ch[2];
var t2 = ch[0] + "" + ch[1] + " " + ch[2];
var t3 = ch[0] + " " + ch[1] + "" + ch[2];
var t4 = ch[0] + "" + ch[1] + "" + ch[2];
Console.WriteLine(t1);
Console.WriteLine(t2);
Console.WriteLine(t3);
Console.WriteLine(t4);
string test2 = "aaa bbb ccc ddd";
var ch2 = test2.Split(' ');
var z1 = ch2[0] + " " + ch2[1] + " " + ch2[2] + " " + ch2[3];
var z2 = ch2[0] + "" + ch2[1] + " " + ch2[2] + " " + ch2[3];
var z3 = ch2[0] + " " + ch2[1] + "" + ch2[2] + " " + ch2[3];
var z4 = ch2[0] + " " + ch2[1] + " " + ch2[2] + "" + ch2[3];
var z5 = ch2[0] + "" + ch2[1] + "" + ch2[2] + " " + ch2[3];
var z6 = ch2[0] + " " + ch2[1] + "" + ch2[2] + "" + ch2[3];
var z7 = ch2[0] + "" + ch2[1] + "" + ch2[2] + "" + ch2[3];
Console.WriteLine(z1);
Console.WriteLine(z2);
Console.WriteLine(z3);
Console.WriteLine(z4);
Console.WriteLine(z5);
Console.WriteLine(z6);
Console.WriteLine(z7);
Console.ReadLine();
}
So if we have n words we have n - 1 possible spaces. Let 0 be absence of space, when 1 be a presence of space:
[0, 0, 0] => Word1Word2Word3Word4
[0, 0, 1] => Word1Word2Word3 Word4
[0, 1, 0] => Word1Word2 Word3Word4
[0, 1, 1] => Word1Word2 Word3 Word4
...
[1, 1, 1] => Word1 Word2 Word3 Word4
So far so good we should enumerate all 2 ^ (n - 1) binary masks:
using System.Collections.Generic;
using System.Linq;
using System.Text;
...
private static IEnumerable<string> Solution(params string[] words) {
return Enumerable
.Range(0, 1 << (words.Length - 1))
.Select(mask => {
StringBuilder sb = new StringBuilder(words[0]);
for (int i = 0; i < words.Length - 1; ++i) {
if ((mask & (1 << i)) != 0)
sb.Append(' ');
sb.Append(words[i + 1]);
}
return sb.ToString();
});
}
Demo (fiddle):
var result = string.Join(Environment.NewLine, Solution("A", "B", "C", "D"));
Console.WriteLine(result);
Output:
ABCD
A BCD
AB CD
A B CD
ABC D
A BC D
AB C D
A B C D
The code you provided works for a limited number of words, but becomes impractical as the number of words increases. A more efficient way to generate all possibilities of a string containing spaces is to use loops and recursion. Here's an example of a function that takes a string and generates all possible combinations of that string (with and without spaces):
private static List<string> GenerateCombinations(string[] words, int index)
{
if (index == words.Length)
{
return new List<string> { "" };
}
var result = new List<string>();
var subCombinations = GenerateCombinations(words, index + 1);
foreach (var subCombination in subCombinations)
{
result.Add(words[index] + subCombination);
result.Add(words[index] + " " + subCombination);
}
return result;
}
You can call this function with the string you want to generate combinations for:
string test = "aaa bbb ccc ddd";
var words = test.Split(' ');
var combinations = GenerateCombinations(words, 0);
foreach(var combination in combinations)
{
Console.WriteLine(combination);
}
The function uses recursion to generate all possible combinations of strings. The index parameter is used to keep track of the current word in the word array, and the recursion stops when the index equals the length of the word array. The function uses two lists to store combinations: one for the current index and one for the next index. The current list is added to the next list in two ways, with and without spaces.
This approach will work for any number of words and will generate all possible combinations efficiently.

String split// manipulation

string keywords = "heard";
string strText = "Have you not heard!! what I said?"
string[] words = strText.Split(' ');
string result = "";
for (int i = 0; i < words.Length; i++)
{
if (words[i].Contains(keywords))
result += "<span>" + words[i] + "</span>" + " ";
else
result += words[i] + " ";
}
I get following output:
Have you not <span>heard!!</span> what I said?
Desired output:
Have you not <span>heard</span>!! what I said?
Can someone guide how can I get the desired output. The strText can only be split with a space.
Use String.Replace
var result = strText.Replace(keywords, "<span>" + keywords + "</span>");
If you have many keywords to replace, then just do replacement in a loop:
string[] keywords = { "heard", "said" };
string result = "Have you not heard!! what I said?";
foreach(var keyword in keywords)
result = result.Replace(keyword, "<span>" + keyword + "</span>");
Alternative solution is regular expression replacement:
string keywords = "heard|said";
string result = "Have you not heard!! what I said?";
result = Regex.Replace(result, keywords, m => "<span>" + m.Value + "</span>");
Why are you even looping through all words? This will give you the same:
string strText = "Have you not heard!! what I said?";
string newText = strText.Replace("heard", "<span>heard</span>");

Select string from certain character until certain character in c#

Okay so my code looks kinda like this
// Returns the note of a favorite pown if it exists
string GetFavoriteNote(int id)
{
string notelist = Properties.Settings.Default.FavoriteNotesList;
// If there's a note, return it
if (notelist.Contains("'" + id + ":"))
{
// What to do here?
}
// If there's no note, return an empty string
else
{
return String.Empty;
}
}
Now it's basically a system where for each id the user can set a note, and it will be saved in this format: 'id:note','id:note',
Now what I want to do is select that note somehow and return it, so I'd have to like select from "'" + id + ":" until the '
If anyone knows how to do this, please help me out.
Thanks
Using a Regex seems like the cleanest approach to me:
string regexFormat = "'{0}:(.*?)'";
Match match = Regex.Match(notelist, string.Format(regexFormat, id));
return match.Success ? match.Groups[1].Value : string.Empty;
Alternatively however, you could use string splitting:
var notes = notelist.Split(',');
var idString = "'" + id + ":";
var note = notes.FirstOrDefault(n => n.StartsWith(idString));
if (note == null) return string.Empty;
return note.Substring(idString.Length, note.Length - (idString.Length + 1));
try
int StartIndex = notelist.IndexOf("'" + id.ToString() + ":");
string result = string.Empty;
if ( StartIndex >= 0 )
{
string tempstr = notelist.SubString ( StartIndex + ("'" + id.ToString() + ":").Length );
result = tempstr.SubString ( 0, tempstr.IndexOf ( "'" ) );
}
return result;
As far I understood your code, following code will kinda give you a solution
string IdWithNote = string.Empty;
string noteList = Properties.Settings.Default.FavoriteNotesList;//your string type note list
List<string> listNote = new List<string>();//newly created string type collection
listNote=noteList.Split(',').ToList<string>();
int index=listNote.IndexOf("'" + id + ":");
if (index > -1)
IdWithNote = listNote[index];
return IdWithNote;
Old fashoned & clear (no regex) Also assumes you only want the text of the note, not the entire note structure.
string key = "'" + id + ":";
int noteStart = noteList.IndexOf(key);
if (noteStart >= 0)
{
int textStart = noteStart + key.Length;
int textEnd = noteList.IndexOf("'", textStart);
return noteList.Substring(textStart, textEnd - textStart);
}
return "";
var myId=2;
var t="'1:note1','2:note2'";
var query = t.Split(',').Select(c => c.Replace("'", "").Split(':')).
Where(c => c[0] == myId.ToString()).
Select(p=>p[1]).First();
Here is a bit of code - the line you really wanted is: retVal = noteList.Substring(startIndex, endIndex - startIndex);
int id = 8;
string noteList = "'8:the note i want','81:the note i do not want'";
string toFind = "'" + id.ToString() + ":";
int startIndex = noteList.IndexOf(toFind) + toFind.Length;
int endIndex = noteList.IndexOf("'", startIndex);
if (noteList.Contains(toFind))
{
retVal = noteList.Substring(startIndex, endIndex - startIndex);
}
else
{
retVal = "nothing found";
}
notelist.Substring(notelist.IndexOf("'" + id + ":"), (notelist.IndexOf("'") - notelist.IndexOf("'" + id + ":")));
this should do the trick, you can select the text by a substring into a new string. substring(startindex, lenght);

Get all instances of sub-string one at a time?

If i have a string containing three 0 values, how would i grab them one by one in order to replace them?
the 0's could be located anywhere in the string.
i don't want to use regex.
example string to parse:
String myString = "hello 0 goodbye 0 clowns are cool 0";
right now i can only find the three 0 values if they are right next to each other. i replace them using stringToParse.Replace("0", "whatever value i want to replace it with");
I want to be able to replace each instance of 0 with a different value...
You can do something like this:
var strings = myString.Split('0');
var replaced = new StringBuilder(strings[0]);
for (var i = 1; i < strings.Length; ++i)
{
replaced.Append("REPLACED " + i.ToString());
replaced.Append(strings[i]);
}
pseudolang :
s = "yes 0 ok 0 and 0"
arr = s.split(" 0")
newstring = arr[0] + replace1 + arr[1] + replace2 + arr[2] + replace3
If you have control of these input strings, then I would use a composite format string instead:
string myString = "hello {0} goodbye {1} clowns are cool {2}";
string replaced = string.Format(myString, "replace0", "replace1", "replace2");
public string ReplaceOne(string full, string match, string replace)
{
int firstMatch = full.indexOf(match);
if(firstMatch < 0)
{
return full;
}
string left;
string right;
if(firstMatch == 0)
left = "";
else
left = full.substring(0,firstMatch);
if(firstMatch + match.length >= full.length)
right = "";
else
right = full.substring(firstMatch+match.length);
return left + replace + right
}
If your match can occur in replace, then you will want to track what index your upto and pass it in to indexOf.
Using LINQ and generic function to decouple replacement logic.
var replace = (index) => {
// put any custom logic here
return (char) index;
};
string input = "hello 0 goodbye 0 clowns are cool 0";
string output = new string(input.Select((c, i) => c == '0' ? replace(i) : c)
.ToArray());
Pros:
Char replacement logic decoupled from the string processing (actually LINQ query)
Cons:
Not the best solution from performance perspectives

Adding a '-' to my string in C#

I Have a string in the form "123456789".
While displaying it on the screen I want to show it as 123-456-789.
Please let me knwo how to add the "-" for every 3 numbers.
Thanks in Advance.
You can use string.Substring:
s = s.Substring(0, 3) + "-" + s.Substring(3, 3) + "-" + s.Substring(6, 3);
or a regular expression (ideone):
s = Regex.Replace(s, #"\d{3}(?=\d)", "$0-");
I'll go ahead and give the Regex based solution:
string rawNumber = "123456789";
var formattedNumber = Regex.Replace(rawNumber, #"(\d{3}(?!$))", "$1-");
That regex breaks down as follows:
( // Group the whole pattern so we can get its value in the call to Regex.Replace()
\d // This is a digit
{3} // match the previous pattern 3 times
(?!$) // This weird looking thing means "match anywhere EXCEPT the end of the string"
)
The "$1-" replacement string means that whenever a match for the above pattern is found, replace it with the same thing (the $1 part), followed by a -. So in "123456789", it would match 123 and 456, but not 789 because it's at the end of the string. It then replaces them with 123- and 456-, giving the final result 123-456-789.
You can use for loop also if the string length is not fixed to 9 digits as follows
string textnumber = "123456789"; // textnumber = "123456789012346" also it will work
string finaltext = textnumber[0]+ "";
for (int i = 1; i < textnumber.Length; i++)
{
if ((i + 1) % 3 == 0)
{
finaltext = finaltext + textnumber[i] + "-";
}
else
{
finaltext = finaltext + textnumber[i];
}
}
finaltext = finaltext.Remove(finaltext.Length - 1);

Categories