public String GetDirectory(String Path)
{
Console.WriteLine("Directorul: ");
var start = Path.IndexOf(":") + 6;
var match2 = Path.Substring(start, Path.IndexOf(".") - start);
return Path;
}
I need to get the path string between the 2 characters in this string:
"C:\Documents\Text.txt"
I want it to show the text between ':' and '.' at the end so :"\Documents\Text"
int start_index = Path.IndexOf(':')+1;
int end_index = Path.LastIndexOf('.');
int length = end_index-start_index;
string directory = Path.Substring(start_index,length);
Linq is always fascinating:
string s = string.Join("",
Path.SkipWhile(p => p != ':')
.Skip(1)
.TakeWhile(p => p != '.')
);
You can use string operations, but you can also use the System.IO.Path functions for a - in my personal opinion - more elegant solution:
string path = #"C:\Documents\Text.txt";
string pathRoot = Path.GetPathRoot(path); // pathRoot will be "C:\", for example
string result = Path.GetDirectoryName(path).Substring(pathRoot.Length - 1) +
Path.DirectorySeparatorChar +
Path.GetFileNameWithoutExtension(path);
Console.WriteLine(result);
you should return your match2 instead of the path since path will remain C:\Documents\Text.txt
public String GetDirectory(String Path)
{
Console.WriteLine("Directorul: ");
var start = Path.IndexOf(":") + 6;
var match2 = Path.Substring(start, Path.IndexOf(".") - start);
return match2;
}
patch = patch.Substring(patch.IndexOf(':') + 1, patch.IndexOf('.') - 2);
Related
I have a string "pencil". The first three letters pen should change to "PEN". Can anyone help me?
You can't "change" a string. You can create a new string and change some of the letters in-flight:
string s1 = "pencil";
string s2 = s1.Substring(0,3).ToUpper() + s1.Substring(3);
You can also, of course, overwrite the existing variable value:
string s1 = "pencil";
s1 = s1.Substring(0,3).ToUpper() + s1.Substring(3);
You can use String.Substring() and String.ToUpper() functions to achieve this
string str = "pencil";
int lettersCount = 3;
str = str.Substring(0, lettersCount ).ToUpper() + str.Substring(lettersCount );
Use Substring and ToUpper:
int numChars = 3;
string pencil = "pencil";
if (pencil.Length >= numChars)
pencil = pencil.Substring(0, numChars).ToUpper() + pencil.Substring(numChars);
using System.IO;
using System;
class Program
{
static void Main()
{
string word = "pencil";
string finalWord = word.Substring(0, 3).ToUpper() + word.Substring(3);
Console.WriteLine(finalWord); //PENcil
}
}
string s = "pencil";
string str = new string(s.Select((c, index) =>
{
if (index < 3)
return Char.ToUpper(c);
else
return c;
}).ToArray());
Console.WriteLine(str); // output: PENcil
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
I have the following code:
var str = "ABC";
var n = 7;
var output = String.Format("{0,n}", str);
This should output the string
" ABC"
How should I change the line above?
Format strings are just strings too - you can define the format separately:
int n = 3;
string format = string.Format("{{0,{0}}}", n);
//or more readable: string format = "{0," + n + "}";
var output = string.Format(format, str);
Edit:
After your update it looks like what you want can also be achieved by PadLeft():
var str = "ABC";
string output = str.PadLeft(7);
Just write:
var lineLength = String.Format("{0," + n + "}", str);
var s="Hello my friend";
string leftSpace = s.PadLeft(20,' '); //pad left with special character
string rightSpace = s.PadRight(20,' '); //pad right with special character
I have a string variable with value
"abcdefghijklmnop".
Now I want to split the string into string array with, say, three characters (the last array element may contain fewer) in each array element from the right end.
I.e.,
"a"
"bcd"
"efg"
"hij"
"klm"
"nop"
What is the easiest and simplest way to do this?? (Both Visual Basic and C# code is welcome)?
Here's a solution:
var input = "abcdefghijklmnop";
var result = new List<string>();
int incompleteGroupLength = input.Length % 3;
if (incompleteGroupLength > 0)
result.Add(input.Substring(0, incompleteGroupLength));
for (int i = incompleteGroupLength; i < input.Length; i+=3)
{
result.Add(input.Substring(i, 3));
}
It gives the expected output of:
"a"
"bcd"
"efg"
"hij"
"klm"
"nop"
Here's something that works - wrapped up into a string extension function.
namespace System
{
public static class StringExts
{
public static IEnumerable<string> ReverseCut(this string txt, int cutSize)
{
int first = txt.Length % cutSize;
int taken = 0;
string nextResult = new String(txt.Take(first).ToArray());
taken += first;
do
{
if (nextResult.Length > 0)
yield return nextResult;
nextResult = new String(txt.Skip(taken).Take(cutSize).ToArray());
taken += cutSize;
} while (nextResult.Length == cutSize);
}
}
}
Usage:
textBox2.Text = "";
var txt = textBox1.Text;
foreach (string s in txt.ReverseCut(3))
textBox2.Text += s + "\r\n";
Regex time!!
Regex rx = new Regex("^(.{1,2})??(.{3})*$");
var matches = rx.Matches("abcdefgh");
var pieces = matches[0].Groups[1].Captures.OfType<Capture>().Select(p => p.Value).Concat(matches[0].Groups[2].Captures.OfType<Capture>().Select(p => p.Value)).ToArray();
pieces will contain:
"ab"
"cde"
"fgh"
(Please, don't use this code! It is only an example of what can happen when you use a regular expression + LINQ.)
Well... here is yet another way I arrived at:
private string[] splitIntoAry(string str)
{
string[] temp = new string[(int)Math.Ceiling((double)str.Length / 3)];
while (str != string.Empty)
{
temp[(int)Math.Ceiling((double)str.Length / 3) - 1] = str.Substring(str.Length - Math.Min(str.Length, 3));
str = str.Substring(0, str.Length - Math.Min(str.Length, 3));
}
return temp;
}
I need to be able to extract a string between 2 tags for example: "00002" from "morenonxmldata<tag1>0002</tag1>morenonxmldata"
I am using C# and .NET 3.5.
Regex regex = new Regex("<tag1>(.*)</tag1>");
var v = regex.Match("morenonxmldata<tag1>0002</tag1>morenonxmldata");
string s = v.Groups[1].ToString();
Or (as mentioned in the comments) to match the minimal subset:
Regex regex = new Regex("<tag1>(.*?)</tag1>");
Regex class is in System.Text.RegularExpressions namespace.
Solution without need of regular expression:
string ExtractString(string s, string tag) {
// You should check for errors in real-world code, omitted for brevity
var startTag = "<" + tag + ">";
int startIndex = s.IndexOf(startTag) + startTag.Length;
int endIndex = s.IndexOf("</" + tag + ">", startIndex);
return s.Substring(startIndex, endIndex - startIndex);
}
A Regex approach using lazy match and back-reference:
foreach (Match match in Regex.Matches(
"morenonxmldata<tag1>0002</tag1>morenonxmldata<tag2>abc</tag2>asd",
#"<([^>]+)>(.*?)</\1>"))
{
Console.WriteLine("{0}={1}",
match.Groups[1].Value,
match.Groups[2].Value);
}
Extracting contents between two known values can be useful for later as well. So why not create an extension method for it. Here is what i do, Short and simple...
public static string GetBetween(this string content, string startString, string endString)
{
int Start=0, End=0;
if (content.Contains(startString) && content.Contains(endString))
{
Start = content.IndexOf(startString, 0) + startString.Length;
End = content.IndexOf(endString, Start);
return content.Substring(Start, End - Start);
}
else
return string.Empty;
}
string input = "Exemple of value between two string FirstString text I want to keep SecondString end of my string";
var match = Regex.Match(input, #"FirstString (.+?) SecondString ").Groups[1].Value;
To get Single/Multiple values without regular expression
// For Single
var value = inputString.Split("<tag1>", "</tag1>")[1];
// For Multiple
var values = inputString.Split("<tag1>", "</tag1>").Where((_, index) => index % 2 != 0);
For future reference, I found this code snippet at http://www.mycsharpcorner.com/Post.aspx?postID=15 If you need to search for different "tags" it works very well.
public static string[] GetStringInBetween(string strBegin,
string strEnd, string strSource,
bool includeBegin, bool includeEnd)
{
string[] result ={ "", "" };
int iIndexOfBegin = strSource.IndexOf(strBegin);
if (iIndexOfBegin != -1)
{
// include the Begin string if desired
if (includeBegin)
iIndexOfBegin -= strBegin.Length;
strSource = strSource.Substring(iIndexOfBegin
+ strBegin.Length);
int iEnd = strSource.IndexOf(strEnd);
if (iEnd != -1)
{
// include the End string if desired
if (includeEnd)
iEnd += strEnd.Length;
result[0] = strSource.Substring(0, iEnd);
// advance beyond this segment
if (iEnd + strEnd.Length < strSource.Length)
result[1] = strSource.Substring(iEnd
+ strEnd.Length);
}
}
else
// stay where we are
result[1] = strSource;
return result;
}
I strip before and after data.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
namespace testApp
{
class Program
{
static void Main(string[] args)
{
string tempString = "morenonxmldata<tag1>0002</tag1>morenonxmldata";
tempString = Regex.Replace(tempString, "[\\s\\S]*<tag1>", "");//removes all leading data
tempString = Regex.Replace(tempString, "</tag1>[\\s\\S]*", "");//removes all trailing data
Console.WriteLine(tempString);
Console.ReadLine();
}
}
}
Without RegEx, with some must-have value checking
public static string ExtractString(string soapMessage, string tag)
{
if (string.IsNullOrEmpty(soapMessage))
return soapMessage;
var startTag = "<" + tag + ">";
int startIndex = soapMessage.IndexOf(startTag);
startIndex = startIndex == -1 ? 0 : startIndex + startTag.Length;
int endIndex = soapMessage.IndexOf("</" + tag + ">", startIndex);
endIndex = endIndex > soapMessage.Length || endIndex == -1 ? soapMessage.Length : endIndex;
return soapMessage.Substring(startIndex, endIndex - startIndex);
}
public string between2finer(string line, string delimiterFirst, string delimiterLast)
{
string[] splitterFirst = new string[] { delimiterFirst };
string[] splitterLast = new string[] { delimiterLast };
string[] splitRes;
string buildBuffer;
splitRes = line.Split(splitterFirst, 100000, System.StringSplitOptions.RemoveEmptyEntries);
buildBuffer = splitRes[1];
splitRes = buildBuffer.Split(splitterLast, 100000, System.StringSplitOptions.RemoveEmptyEntries);
return splitRes[0];
}
private void button1_Click(object sender, EventArgs e)
{
string manyLines = "Received: from exim by isp2.ihc.ru with local (Exim 4.77) \nX-Failed-Recipients: rmnokixm#gmail.com\nFrom: Mail Delivery System <Mailer-Daemon#isp2.ihc.ru>";
MessageBox.Show(between2finer(manyLines, "X-Failed-Recipients: ", "\n"));
}