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

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

Related

Reverse Words at odd position only C#

This is my code. How can I edit it to show every word which is at the odd position ONLY to be reversed?
for (int i = input.Length - 1; i >= 0; i--)
{
if (input[i] == ' ')
{
result = tmp + " " + result;
tmp = "";
}
else
tmp += input[i];
}
result = tmp + " " + result;
Console.WriteLine(result);
Example input:
"How are you today"
to output:
"How era you yadot"
Based on the position of a word ['How' -> 0] do not reverse; [are -> 1 odd index] Reverse
You can achieve it with the help of LINQ:
var input = "hello this is a test message";
var inputWords = input.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
var result = string.Join(" ",
inputWords.Select((w, i) =>
i % 2 == 0
? w
: new string(w.Reverse().ToArray())
));
Where w in the select is the word, and i is the index, starting at 0 for the first word. % is the modulus operator and gets the remainder. If i % 2 == 0 (i.e. i can be divided by 2 with no remainder), then the original is returned. If there is a remainder (odd) then the reversed word is returned. Finally, it's all wrapped up in a string.Join(" ", items); which turns it back into a normal string rather than an array of items.
Try it online
So far you have a string, like this:
string input = "I want to reverse all odd words (odd words only!).";
And you, naturally, want to perform the task. Now it's the main question what's an odd word?
If you mean word's position (I at position 0, want at 1 - should be reversed etc.)
then you can use regular expressions to match words and Linq to process them:
using System.Linq; // To reverse single word
using System.Text.RegularExpressions; // To match the words within the text
...
// Let's elaborate the test example: add
// 1. some punctuation - ()!. - to preserve it
// 2. different white spaces (spaces and tabulation - \t)
// to add difficulties for naive algorithms
// 3. double spaces (after "to") to mislead split based algorithms
string input = "I want to reverse all\todd words (odd words only!).";
int index = 0; // words' indexes start from zero
string result = Regex.Replace(
input,
"[A-Za-z']+", // word is letters and apostrophes
match => index++ % 2 == 0
? match.Value // Even words intact
: string.Concat(match.Value.Reverse())); // Odd words reversed
Console.WriteLine(result);
If you want to reverse the words with odd Length, i.e. I, all, odd then all you have to do is to change the condition to
match => match.Value % 2 == 0
Outcome:
I tnaw to esrever all ddo words (ddo words ylno!).
Please, notice, that the punctuation has been preserved (only words are reversed).
OP: Based on the position of a word ['How' -> 0] do not reverse; [are -> 1 odd index] Reverse
public static void Main()
{
string input = "How are you today Laken-C";
//As pointed out by #Dmitry Bychenko string input = "How are you today";
//(double space after How) leads to How are uoy today outcome
input = Regex.Replace(input, #"\s+", " ");
var inp = input.Split(' ').ToList();
for (int j = 0; j < inp.Count(); j++)
{
if(j % 2 == 1)
{
Console.Write(inp[j].Reverse().ToArray());
Console.Write(" ");
}
else
Console.Write(inp[j] + " ");
}
}
OUTPUT:
DEMO:
dotNetFiddle
try this is perfect working code..
static void Main(string[] args)
{
string orgstr = "my name is sagar";
string revstr = "";
foreach (var word in orgstr.Split(' '))
{
string temp = "";
foreach (var ch in word.ToCharArray())
{
temp = ch + temp;
}
revstr = revstr + temp + " ";
}
Console.Write(revstr);
Console.ReadKey();
}
Output: ym eman si ragas

How do I alternate the case in a string?

I need to alternate the case in a sentence and I don't know how to.
For example:
thequickbrownfoxjumpsoverthelazydog
to
GoDyZaLeHtReVoSpMuJxOfNwOrBkCiUqEhT
this is my code so far
Console.WriteLine("Please enter a sentence:");
string text = Console.ReadLine();
text = text.Replace(" ", "");
char[] reversed = text.ToCharArray();//String to char
Array.Reverse(reversed);//Reverses char
new string(reversed);//Char to string
Console.WriteLine(reversed);
Console.ReadLine();
Please note that there are no spaces for a reason as that's also part of the homework task.
A string is immutable, so, you need to convert it to a char[].
char[] characters = text.ToCharArray();
for (int i = 0; i < characters.Length; i+=2) {
characters[i] = char.ToUpper(characters[i]);
}
text = new string(characters);
There is no point to reverse your string. Just upper case your even number indexed characters in your string.
Remember, my culture is tr-TR and this String.ToUpper method works depends on your current thread culture. In this example, your output can be different than mine.
Here an example in LINQPad;
string s = "thequickbrownfoxjumpsoverthelazydog";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.Length; i++)
{
if (i % 2 == 0)
{
sb.Append(s[i].ToString().ToUpper());
}
else
{
sb.Append(s[i].ToString());
}
}
sb.ToString().Dump();
Output will be;
ThEqUiCkBrOwNfOxJuMpSoVeRtHeLaZyDoG
Another possible solution with LINQ can be done in one line like this:
string s = "thequickbrownfoxjumpsoverthelazydog";
string result = new String(s
// take each character
.ToCharArray()
// convert every character at even index to upper
.Select ((character, index) => (index % 2) == 0 ? Char.ToUpper(character) : character)
// back to array in order to create a string
.ToArray());
Console.WriteLine(result);
The output is:
ThEqUiCkBrOwNfOxJuMpSoVeRtHeLaZyDoG
This solution uses the indexed LINQ Select clause in order to access the current index and the value that is currently projected.
A one liner:
new string(myString.Select((c, i) => i % 2 == 0 ? char.ToUpper(c) : c).ToArray())
An extension method:
public static string AltCase(this string s)
{
return new string(s.Select((c, i) => i % 2 == 0 ? char.ToUpper(c) : c).ToArray());
}

Substring from specific sign to sign

I have a list of strings in format like this:
Web.WebClient.Areas.Scada.Services.IScadaManualOverrideService,Web.WebClient.TDMSWebApp
I need only the part from comma sign to the first dot sign.
For example above it should return this string: IScadaManualOverrideService
Anyone has an idea how can I do this and get substrings if I have list of strings like first one?
from comma sign to the first dot sign
You mean from dot to comma?
You can split the string by comma first, then split by dot and take the last:
string text = "Web.WebClient.Areas.Scada.Services.IScadaManualOverrideService,Web.WebClient.TDMSWebApp";
string result = text.Split(',')[0].Split('.').Last(); // IScadaManualOverrideService
Splitting strings is not what can be called effective solution. Sorry can't just pass nearby.
So here is another one
string text = "Web.WebClient.Areas.Scada.Services.IScadaManualOverrideService,Web.WebClient.TDMSWebApp";
var end = text.IndexOf(',');
var start = text.LastIndexOf('.', end) + 1;
var result = text.Substring(start, end - start);
Proof woof woof.
Bullet-proof version (ugly)
string text = "IScadaManualOverrideService";
//string text = "Services.IScadaManualOverrideService";
//string text = "IScadaManualOverrideService,";
//string text = "";
var end = text.IndexOf(',');
var start = text.LastIndexOf('.', (end == -1 ? text.Length - 1 : end)) + 1;
var result = text.Substring(start, (end == -1 ? text.Length : end) - start);
Insert this if hacker attack is expected
if(text == null)
return "Stupid hacker, die!";
string s = "Web.WebClient.Areas.Scada.Services.IScadaManualOverrideService,Web.WebClient.TDMSWebApp";
string s1 = s.Substring(0, s.IndexOf(","));
string s2 = s1.Substring(s1.LastIndexOf(".") + 1);
string input = "Web.WebClient.Areas.Scada.Services.IScadaManualOverrideService,Web.WebClient.TDMSWebApp";
int commaIndex = input.IndexOf(',');
string remainder = input.Substring(0, commaIndex);
int dotIndex = remainder.LastIndexOf('.');
string output = remainder.Substring(dotIndex + 1);
This can be written a lot shorter, but for the explanation i think this is more clear
sampleString.Split(new []{','})[0].Split(new []{'.'}).Last()
string s = "Web.WebClient.Areas.Scada.Services.IScadaManualOverrideService,Web.WebClient.TDMSWebApp";
string subStr = new string(s.TakeWhile(c => c != ',').ToArray());
string last = new string(subStr.Reverse().TakeWhile(c => c != '.').Reverse().ToArray());
Console.WriteLine(last); // output: IScadaManualOverrideService

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

Help with string manipulation function

I have a set of strings that contain within them one or more question marks delimited by a comma, a comma plus one or more spaces, or potentially both. So these strings are all possible:
BOB AND ?
BOB AND ?,?,?,?,?
BOB AND ?, ?, ? ,?
BOB AND ?,? , ?,?
?, ? ,? AND BOB
I need to replace the question marks with #P#, so that the above samples would become:
BOB AND #P1
BOB AND #P1,#P2,#P3,#P4,#P5
BOB AND #P1,#P2,#P3,#P4
BOB AND #P1,#P2,#P3,#P4
#P1,#P2,#P3 AND BOB
What's the best way to do this without regex or Linq?
I ignored the trimming of spaces in your output example, because if this is to be used in a SQL statement, the spaces are irrelevent. This should perform pretty well due to the use of StringBuilder rather than repeated calls to Replace, Substring, or other string methods.:
public static string GetParameterizedString(string s)
{
var sb = new StringBuilder();
var sArray = s.Split('?');
for (var i = 0; i < sArray.Length - 1; i++)
{
sb.Append(sArray[i]);
sb.Append("#P");
sb.Append(i + 1);
}
sb.Append(sArray[sArray.Length - 1]);
return sb.ToString();
}
If you don't want regex or LINQ, I would just write a loop, and use the "ReplaceFirst" method from this question to loop over the string, replacing each occurrence of ? with the appropriate #P#.\
How do I replace the *first instance* of a string in .NET?
Maybe something like this:
int i = 0;
while (myString.Contains("?"))
{
myString = myString.ReplaceFirst("?", "#P" + i);
i++;
}
Note that "ReplaceFirst" is not a standard method on string - you have to implement it (e.g. as an extension method, in this example).
Why not generate your SQL as you get your parameters defining proper CASE in your code and give it to execution at the very end when it is ready?
If you want something out of the box :)
string toFormat = "?, ? ,? AND BOB";
while (toFormat.Contains(" "))
toFormat = toFormat.Replace(" ", " ");
toFormat = toFormat.Replace("?", "{0}");
string formated = string.Format(toFormat, new PCounter());
Where PCounter is like this
class PCounter{
int i = 0;
public override string ToString(){
return "#P" + (++i);
}
}
I think something like the below should do it.
string input = "BOB AND ?,?,?,?,?";
int number = 1;
int index = input.IndexOf("?");
while (index > -1)
{
input = input.Substring(0, index).Trim() + " #P" + number++.ToString() + input.Substring(index + 1).Trim();
index = input.IndexOf("?");
}

Categories