Select a substring from string - c#

I have a string as follows:
string str = "abcdefgh"
and I would like to reduce the size to only two chars - so the output would be:
str = "ab"

string str = "abcdefgh";
var s = str.Substring(0, 2);
Or another solution is to write Your Own extension method (that would check if string longer than expected substring and avoid the exception as athoik has noticed) and do this
class Program
{
static void Main(string[] args)
{
var str = "asdfasd";
var trimmed = str.MySubString(2);
Console.WriteLine(trimmed);
Console.ReadLine();
}
}
public static class Helper
{
public static string MySubString(this String value, int length)
{
return !string.IsNullOrEmpty(value) && value.Length >= length
? value.Substring(0, length)
: value;
}
}

string sub = str.Substring(0, 2);

string substr = str.substring(0,2)
or
StringBuilder sb = new StringBuilder();
sb.toString(0,2);

Related

how do find the same string and difference string in List<string>?

I have list like this:
List<string> myList = new List<string>()
{
"AS2258B43C014AI9954803",
"AS2258B43C014AI9954603",
"AS2258B43C014AI9954703",
"AS2258B43C014AI9954503",
"AS2258B43C014AI9954403",
"AS2258B43C014AI9954203",
"AS2258B43C014AI9954303",
"AS2258B43C014AI9954103",
};
I want to output something format is sameString+diffString0\diffString1\diffString2.... like this "AS2258B43C014AI9954803\603\703\503\403\203\303\103"
what should I do?
You can create a method which returns you the difference between to strings:
private static string GetDiff (string s1, string s2)
{
int i;
for(i = 0; i < Math.Min(s1.Length,s2.Length); i++)
{
if(s1[i] != s2[i])
{
break;
}
}
return s2.Substring(i);
}
This method iterats until the first character which is different and returns the remaining characters of the second string.
With that method, you can obtain your result with the LINQ query:
string first = myList[0];
string result = first + "/" + string.Join("/", myList.Skip(1).Select(x => GetDiff(first,x)));
Online demo: https://dotnetfiddle.net/TPkhmz
Alphanumeric sorting using LINQ
Create static method for pads
public static string PadNumbers(string input)
{
return Regex.Replace(input, "[0-9]+", match => match.Value.PadLeft(10, '0'));
}
then call it
var result = myList.OrderBy(x => PadNumbers(x));
after that you can find the difference
The simplest solution is to create a function like this :
public static string Output(List<String> ListString)
{
string sameString = ListString.First().Substring(0, 18);
string output = sameString;
foreach (var item in ListString)
{
output += item.Substring(19);
output += "\\";
}
return output.Substring(0, output.Length - 1);
}

c#- How can I format an output so that a string always takes up 7 digits?

string name1 = "John";
string name2 = "Alexander";
Console.WriteLine(??);
//desired output:
John Alexand
How can I format the strings so that they will always take up 7 spaces? I'm familiar with how to do this in C, but I cannot find a way to do it for C#.
Use PadRight and SubString
var a = "James";
Console.WriteLine(a.PadRight(7, ' ').Substring(0, 7));
Formatting like $"{name, 7}" ensures that the result will have length at least 7; however, longer inputs will not be trimmed (i.e. "Alexander" will not be trimmed to "Alexand").
We have to impement the logic manually and I suggest hiding it in an extension method:
public static class StringExtensions {
public static string ToLength(this string source, int length) {
if (length < 0)
throw new ArgumentOutOfRangeException("length");
else if (length == 0)
return "";
else if (string.IsNullOrEmpty(source))
return new string(' ', length);
else if (source.Length < length)
return source.PadRight(length);
else
return source.Substring(0, length);
}
}
usage:
Console.WriteLine($"{name1.ToLength(7)} {name2.ToLength(7)}");
I would use an extension method coupled with PadRight()
public void Main() {
string name1 = "John";
string name2 = "Alexander";
string FullName = name1.FixLeft(7) + name2.FixLeft(7);
Console.WriteLine(FullName);
}
private static string FixLeft(this string TextInput, int DesiredLength) {
if (TextInput.Length < DesiredLength) { return TextInput.PadRight(DesiredLength); }
else { return TextInput.Substring(0,DesiredLength); }
}

Split the string after a word

I want to split a string after a word, not after the character.
Example string:
A-quick-brown-fox-jumps-over-the-lazy-dog
I want to split the string after "jumps-"
can I use the stringname.Split("jumps-") function?
I want the following output:
over-the-lazy-dog.
I suggest using IndexOf and Substring since you actually want a suffix ("String after word"), not a split:
string source = "A-quick-brown-fox-jumps-over-the-lazy-dog";
string split = "jumps-";
// over-the-lazy-dog
string result = source.Substring(source.IndexOf(split) + split.Length);
var theString = "A-quick-brown-fox-jumps-over-the-lazy-dog.";
var afterJumps = theString.Split(new[] { "jumps-" }, StringSplitOptions.None)[1]; //Index 0 would be what is before 'jumps-', index 1 is after.
I usually use extension methods:
public static string join(this string[] strings, string delimiter) { return string.Join(delimiter, strings); }
public static string[] splitR(this string str, params string[] delimiters) { return str.Split(delimiters, StringSplitOptions.RemoveEmptyEntries); }
//public static string[] splitL(this string str, string delimiter = " ", int limit = -1) { return vb.Strings.Split(str, delimiter, limit); }
public static string before(this string str, string delimiter) { int i = (str ?? ""). IndexOf(delimiter ?? ""); return i < 0 ? str : str.Remove (i ); } // or return str.splitR(delimiter).First();
public static string after (this string str, string delimiter) { int i = (str ?? "").LastIndexOf(delimiter ?? ""); return i < 0 ? str : str.Substring(i + delimiter.Length); } // or return str.splitR(delimiter).Last();
sample use:
stringname.after("jumps-").splitR("-"); // splitR removes empty entries
You could extend the Split() method. In fact, I did this a few months ago. Probably not the prettiest code but it gets the job done. This method splits at every jumps-, not just at the first one.
public static class StringExtensions
{
public static string[] Split(this String Source, string Separator)
{
if (String.IsNullOrEmpty(Source))
throw new Exception("Source string is null or empty!");
if (String.IsNullOrEmpty(Separator))
throw new Exception("Separator string is null or empty!");
char[] _separator = Separator.ToArray();
int LastMatch = 0;
List<string> Result = new List<string>();
Func<char[], char[], bool> Matches = (source1, source2) =>
{
for (int i = 0; i < source1.Length; i++)
{
if (source1[i] != source2[i])
return false;
}
return true;
};
for (int i = 0; _separator.Length + i < Source.Length; i++)
{
if (Matches(_separator.ToArray(), Source.Substring(i, _separator.Length).ToArray()))
{
Result.Add(Source.Substring(LastMatch, i - LastMatch));
LastMatch = i + _separator.Length;
}
}
Result.Add(Source.Substring(LastMatch, Source.Length - LastMatch));
return Result.ToArray();
}
}

Replacing a char at a given index in string? [duplicate]

This question already has answers here:
how do I set a character at an index in a string in c#?
(7 answers)
Closed 5 years ago.
String does not have ReplaceAt(), and I'm tumbling a bit on how to make a decent function that does what I need. I suppose the CPU cost is high, but the string sizes are small so it's all ok
Use a StringBuilder:
StringBuilder sb = new StringBuilder(theString);
sb[index] = newChar;
theString = sb.ToString();
The simplest approach would be something like:
public static string ReplaceAt(this string input, int index, char newChar)
{
if (input == null)
{
throw new ArgumentNullException("input");
}
char[] chars = input.ToCharArray();
chars[index] = newChar;
return new string(chars);
}
This is now an extension method so you can use:
var foo = "hello".ReplaceAt(2, 'x');
Console.WriteLine(foo); // hexlo
It would be nice to think of some way that only required a single copy of the data to be made rather than the two here, but I'm not sure of any way of doing that. It's possible that this would do it:
public static string ReplaceAt(this string input, int index, char newChar)
{
if (input == null)
{
throw new ArgumentNullException("input");
}
StringBuilder builder = new StringBuilder(input);
builder[index] = newChar;
return builder.ToString();
}
... I suspect it entirely depends on which version of the framework you're using.
string s = "ihj";
char[] array = s.ToCharArray();
array[1] = 'p';
s = new string(array);
Strings are immutable objects, so you can't replace a given character in the string.
What you can do is you can create a new string with the given character replaced.
But if you are to create a new string, why not use a StringBuilder:
string s = "abc";
StringBuilder sb = new StringBuilder(s);
sb[1] = 'x';
string newS = sb.ToString();
//newS = "axc";
I suddenly needed to do this task and found this topic.
So, this is my linq-style variant:
public static class Extensions
{
public static string ReplaceAt(this string value, int index, char newchar)
{
if (value.Length <= index)
return value;
else
return string.Concat(value.Select((c, i) => i == index ? newchar : c));
}
}
and then, for example:
string instr = "Replace$dollar";
string outstr = instr.ReplaceAt(7, ' ');
In the end I needed to utilize .Net Framework 2, so I use a StringBuilder class variant though.
If your project (.csproj) allow unsafe code probably this is the faster solution:
namespace System
{
public static class StringExt
{
public static unsafe void ReplaceAt(this string source, int index, char value)
{
if (source == null)
throw new ArgumentNullException("source");
if (index < 0 || index >= source.Length)
throw new IndexOutOfRangeException("invalid index value");
fixed (char* ptr = source)
{
ptr[index] = value;
}
}
}
}
You may use it as extension method of String objects.
public string ReplaceChar(string sourceString, char newChar, int charIndex)
{
try
{
// if the sourceString exists
if (!String.IsNullOrEmpty(sourceString))
{
// verify the lenght is in range
if (charIndex < sourceString.Length)
{
// Get the oldChar
char oldChar = sourceString[charIndex];
// Replace out the char ***WARNING - THIS CODE IS WRONG - it replaces ALL occurrences of oldChar in string!!!***
sourceString.Replace(oldChar, newChar);
}
}
}
catch (Exception error)
{
// for debugging only
string err = error.ToString();
}
// return value
return sourceString;
}

Append certain number of characters from a string to another string

This is a pretty basic question, but here it goes: Is there a string method in C# that adds a number of characters from a string to another string? In C++ std::string class, there was the append method that had three parameters: source string, indexStart, offset.
string a = "foo";
string b = "bar";
a.append(b, 0, 2); // a is now "fooba";
In C# I also tried with StringBuilder, but no luck.
Strings in .NET are immutable. Once a string is created, you can't modify it. However, you can create a new string by concatenation, and reassign it to the same variable:
string a = "foo";
string b = "bar";
a = a + b.Substring(0, 2); // a is now "fooba";
string a = "foo";
string b = "bar";
var sb = new StringBuilder();
sb.append(a);
sb.append(b.SubString(0,2));
string res = sb.ToString(); // res = "fooba"
If you're feeling adventurous, you could also write an extension method:
public static class MyStringExtensions
{
public static string Append(this string original, string textToAdd, int length)
{
if (length <= 0)
{
return original;
}
var len = (textToAdd.Length < length)
? textToAdd.Length
: length;
return original + textToAdd.Substring(0, len);
}
}
Then to use it you would go like this:
string a = "foo".Append("bar", 2);
or
string a = "foo";
string b = "bar";
string c = a.Append(b, 2);
This also has the nice advantage of allowing error/exception handling in a central location.
Try doing
string aa = "foo";
string bb = "bad";
bb= string.Concat(aa, bb.Substring(0, 2));

Categories

Resources