How to get the remaining string after removing a substring - c#

Suppose, I have the following string:
string temp = "some string contains text which contains demo";
string result = RemainingString(temp, 12, 8); // string, startIndex, length
The result string I need should look as follows:
some string text which contains demo
Note, that the word contains is removed from first place only.
Update: I personally want to achieve this using regular expression explicitly.

Try the String.Remove method, it does exactly what you ask.

String.Remove(Int32, Int32) will do the job:
string temp = "some string contains text which contains demo";
string result = temp.Remove(12,8);

Use string.Remove:
public string RemainingString(string orig, int startIndex, int length)
{
return orig.Remove(startIndex, length);
}
Alternatively - concatenate two substrings - up to the index, and after the index+length (.NET 1.0/1.1):
public string RemainingString(string orig, int startIndex, int length)
{
return orig.Substring(0, startIndex) +
orig.Substring(startIndex + length);
}

Here's a solution using regular expressions:
public string RemainingString(string str, int start, int length)
{
return Regex.Replace(str, "^(.{" + start+ "})(?:.{" + length + "})(.*)$", "$1$2");
}

$line_string = 'this is all the sting from which i would want to treat';
$key_string ='from which';
//use strpos
$position2 = strpos($line_string,$key);
if($position2){
$found = substr($line_string,$position2,strlen($key_string));
//echo $found;
}
//the substr now begins at character position $position2
//and ends at position2 + strlen($key_string);
//so
$remainderpos = position2 + strlen($key_string);
$str_remaining = substr($line_string,$remainderpos);
echo $str_remaining;
as simple as it can get. code from the scratch.

Related

ASP.Net - Masked first 6 character on a string with dynamic length

is it possible to masked a first 6 characters on a string if the string is dynamics on it's length?
Example, I have a string "test123456789" and I want a result of "******3456789" or a string of "1234test" and I want a result of "******st". All I'm seeing sample codes here in masking are strings with a static length. Can anyone kindly help me with this? Thank you so much in advance.
Yes, it's possible, and even quite easy, using simple string concatenation and SubString:
var original = "Some string here";
var target = "******" + ((original.Length > 6) ? original.Substring(6) : "") ;
If you want shorter strings to mask all characters but keep original length, you can do it like this:
var target = new string('*', Math.Min(original.Length, 6)) + ((original.Length > 6) ? original.Substring(6) : "") ;
This way, an input of "123" would return 3 asterisks ("***"). The first code I've shown will return 6 asterisks ("******")
Linq is an alternative to Substring and ternary operator solution (see Zohar Peled's answer):
using System.Linq;
...
string original = "Some string here";
string result = "******" + string.Concat(original.Skip(6));
If you want to preserve the length of short (less than 6 character string):
// if original shorter than 6 symbols, e.g. "short"
// we'll get "*****" (Length number of *, not 6)
// if original has six or more symbols, e.g. "QuiteLong"
// we'll get "******ong" as usual
string original = "short";
...
string result = new string('*', Math.Min(6, original.Length)) +
string.Concat(original.Skip(Math.Min(6, original.Length)));
You may want to have the routine as an extension method:
public static partial class StringExtensions {
public static string MaskPrefix(this string value, int count = 6) {
if (null == value)
throw new ArgumentNullException("value"); // or return value
else if (count < 0)
throw new ArgumentOutOfRangeException("count"); // or return value
int length = Math.Min(value.Length, count);
return new string('*', length) + string.Concat(value.Skip(length));
}
}
And so you can put as if string has MaskPrefix method:
string original = "Some string here";
string result = original.MaskPrefix(6);
You can substring and mask it. Make sure to check if the input string is lower than 6 as below sample
string str = "123456789345798";
var strResult = "******"+str.Substring(6, str.Length - 6);
Console.WriteLine("strResult :" + strResult);

how to do substring in reverse mode in c#

My string is "csm15+abc-indiaurban#v2". I want only "indiaurban" from my string. what I am doing right now is :
var lastindexofplusminus = input.LastIndexOfAny(new char[]{'+','-'});
var lastindexofattherate = input.LastIndexOf('#');
string sub = input.Substring(lastindexofplusminus,lastindexofattherate);
but getting error "Index and length must refer to a location within the string."
Thanks in Advance.
You should put the length in the second argument (instead of passing another index) of the Substring you want to grab. Given that you know the two indexes, the translation to the length is pretty straight forward:
string sub = input.Substring(lastindexofplusminus + 1, lastindexofattherate - lastindexofplusminus - 1);
Note, +1 is needed to get the char after your lastindexofplusminus.
-1 is needed to get the Substring between them minus the lastindexofattherate itself.
You can simple reverse the string, apply substring based on position and length, than reverse again.
string result = string.Join("", string.Join("", teste.Reverse()).Substring(1, 10).Reverse());
Or create a function:
public static string SubstringReverse(string str, int reverseIndex, int length) {
return string.Join("", str.Reverse().Skip(reverseIndex - 1).Take(length));
}
View function working here!!
You can use LINQ:
string input = "csm15+abc-indiaurban#v2";
string result = String.Join("", input.Reverse()
.SkipWhile(c => c != '#')
.Skip(1)
.TakeWhile(c => c != '+' && c != '-')
.Reverse());
Console.WriteLine(result); // indiaurban
I don't know what is identify your break point but here is sample which is working
you can learn more about this at String.Substring Method (Int32, Int32)
String s = "csm15+abc-indiaurban#v2";
Char charRange = '-';
Char charEnd = '#';
int startIndex = s.IndexOf(charRange);
int endIndex = s.LastIndexOf(charEnd);
int length = endIndex - startIndex - 1;
Label1.Text = s.Substring(startIndex+1, length);
Assuming that your string is always in that format
string str = "csm15+abc-indiaurban#v2";
string subSTr = str.Substring(10).Substring(0,10);

Changing a specific part of a string

In C#, I got a string which looks in the following format:
a number|a number|a number,a number
for example: 1|2|3,4
I consider each number as the different part of the string. in the previous example, 1 is the first part, 2 is the second and so on.
I want to be able to replace a specific part of the string given an index of the part I want to change.
It's not that hard to do it with String.Split but that part with the comma makes it tedious since then i need to check if the index is 3 or 4 and then also separate with the comma.
Is there a more elegant way to do a switch of a specific part in the string? maybe somehow with a regular expression?
EDIT: I will add some requirements which I didn't write before:
What if I want to for example take the 3rd part of the string and replace it with the number there and add it 2. for example 1|2|3,4 to 1|2|5,4 where the 5 is NOT a constant but depends on the input string given.
You can create the following method
static string Replace(string input, int index, string replacement)
{
int matchIndex = 0;
return Regex.Replace(input, #"\d+", m => matchIndex++ == index ? replacement : m.Value);
}
Usage:
string input = "1|2|3,4";
string output = Replace(input, 1, "hello"); // "1|hello|3,4
As Eric Herlitz suggested, you can use other regex, the negative of delimiters. For example, if you expect , and | delimiters, you can replace \d+ by [^,|]+ regex. If you expect ,, | and # delimiters, you can use [^,|#] regex.
If you need to do some mathematical operations, you're free to do so:
static string Replace(string input, int index, int add)
{
int matchIndex = 0;
return Regex.Replace(input, #"\d+", m => matchIndex++ == index ? (int.Parse(m.Value) + add).ToString() : m.Value );
}
Example:
string input = "1|2|3,4";
string output = Replace(input, 2, 2); // 1|2|5,4
You can even make it generic:
static string Replace(string input, int index, Func<string,string> operation)
{
int matchIndex = 0;
return Regex.Replace(input, #"\d+", m => matchIndex++ == index ? operation(m.Value) : m.Value);
}
Example:
string input = "1|2|3,4";
string output = Replace(input, 2, value => (int.Parse(value) + 2).ToString()); // 1|2|5,4
Try this:
static void Main()
{
string input = "1|2|3|4,5,6|7,8|9|23|29,33";
Console.WriteLine(ReplaceByIndex(input, "hello", 23));
Console.ReadLine();
}
static string ReplaceByIndex(string input, string replaceWith, int index)
{
int indexStart = input.IndexOf(index.ToString());
int indexEnd = input.IndexOf(",", indexStart);
if (input.IndexOf("|", indexStart) < indexEnd)
indexEnd = input.IndexOf("|", indexStart);
string part1 = input.Substring(0, indexStart);
string part2 = "";
if (indexEnd > 0)
{
part2 = input.Substring(indexEnd, input.Length - indexEnd);
}
return part1 + replaceWith + part2;
}
This is assuming the numbers are in ascending order.
Use Regex.Split for the input and Regex.Match to collect your delimiters
string input = "1|2|3,4,5,6|7,8|9";
string pattern = #"[,|]+";
// Collect the values
string[] substrings = Regex.Split(input, pattern);
// Collect the delimiters
MatchCollection matches = Regex.Matches(input, pattern);
// Replace anything you like, i.e.
substrings[3] = "222";
// Rebuild the string
int i = 0;
string newString = string.Empty;
foreach (string substring in substrings)
{
newString += string.Concat(substring, matches.Count >= i + 1 ? matches[i++].Value : string.Empty);
}
This will output "1|2|3,222,5,6|7,8|9"
Try this (tested):
public static string Replace(string input, int value, int index)
{
string pattern = #"(\d+)|(\d+)|(\d+),(\d+)";
return Regex.Replace(input, pattern, match =>
{
if (match.Index == index * 2) //multiply by 2 for | and , character.
{
return value.ToString();
}
return match.Value;
});
}
Usage example:
string input = "1|2|3,4";
string output = Replace(input, 9, 1);
Updated with new requirement:
public static string ReplaceIncrement(string input, int incrementValue, int index)
{
string pattern = #"(\d+)|(\d+)|(\d+),(\d+)";
return Regex.Replace(input, pattern, match =>
{
if (match.Index == index * 2)
{
return (int.Parse(match.Value) + incrementValue).ToString();
}
return match.Value;
});
}

How to Remove the last char of String in C#?

I have a numeric string, which may be "124322" or "1231.232" or "132123.00".
I want to remove the last char of my string (whatever it is).
So I want if my string is "99234" became "9923".
The length of string is variable. It's not constant so I can not use string.Remove or trim or some like them(I Think).
How do I achieve this?
YourString = YourString.Remove(YourString.Length - 1);
var input = "12342";
var output = input.Substring(0, input.Length - 1);
or
var output = input.Remove(input.Length - 1);
newString = yourString.Substring(0, yourString.length -1);
If this is something you need to do a lot in your application, or you need to chain different calls, you can create an extension method:
public static String TrimEnd(this String str, int count)
{
return str.Substring(0, str.Length - count);
}
and call it:
string oldString = "...Hello!";
string newString = oldString.TrimEnd(1); //returns "...Hello"
or chained:
string newString = oldString.Substring(3).TrimEnd(1); //returns "Hello"
If you are using string datatype, below code works:
string str = str.Remove(str.Length - 1);
But when you have StringBuilder, you have to specify second parameter length as well.
That is,
string newStr = sb.Remove(sb.Length - 1, 1).ToString();
To avoid below error:

How to get the last five characters of a string using Substring() in C#?

I can get the first three characters with the function below.
However, how can I get the output of the last five characters ("Three") with the Substring() function? Or will another string function have to be used?
static void Main()
{
string input = "OneTwoThree";
// Get first three characters
string sub = input.Substring(0, 3);
Console.WriteLine("Substring: {0}", sub); // Output One.
}
If your input string could be less than five characters long then you should be aware that string.Substring will throw an ArgumentOutOfRangeException if the startIndex argument is negative.
To solve this potential problem you can use the following code:
string sub = input.Substring(Math.Max(0, input.Length - 5));
Or more explicitly:
public static string Right(string input, int length)
{
if (length >= input.Length)
{
return input;
}
else
{
return input.Substring(input.Length - length);
}
}
string sub = input.Substring(input.Length - 5);
If you can use extension methods, this will do it in a safe way regardless of string length:
public static string Right(this string text, int maxLength)
{
if (string.IsNullOrEmpty(text) || maxLength <= 0)
{
return string.Empty;
}
if (maxLength < text.Length)
{
return text.Substring(text.Length - maxLength);
}
return text;
}
And to use it:
string sub = input.Right(5);
static void Main()
{
string input = "OneTwoThree";
//Get last 5 characters
string sub = input.Substring(6);
Console.WriteLine("Substring: {0}", sub); // Output Three.
}
Substring(0, 3) - Returns substring of first 3 chars. //One
Substring(3, 3) - Returns substring of second 3 chars. //Two
Substring(6) - Returns substring of all chars after first 6. //Three
One way is to use the Length property of the string as part of the input to Substring:
string sub = input.Substring(input.Length - 5); // Retrieves the last 5 characters of input
Here is a quick extension method you can use that mimics PHP syntax. Include AssemblyName.Extensions to the code file you are using the extension in.
Then you could call:
input.SubstringReverse(-5) and it will return "Three".
namespace AssemblyName.Extensions {
public static class StringExtensions
{
/// <summary>
/// Takes a negative integer - counts back from the end of the string.
/// </summary>
/// <param name="str"></param>
/// <param name="length"></param>
public static string SubstringReverse(this string str, int length)
{
if (length > 0)
{
throw new ArgumentOutOfRangeException("Length must be less than zero.");
}
if (str.Length < Math.Abs(length))
{
throw new ArgumentOutOfRangeException("Length cannot be greater than the length of the string.");
}
return str.Substring((str.Length + length), Math.Abs(length));
}
}
}
Substring. This method extracts strings. It requires the location of the substring (a start index, a length). It then returns a new string with the characters in that range.
See a small example :
string input = "OneTwoThree";
// Get first three characters.
string sub = input.Substring(0, 3);
Console.WriteLine("Substring: {0}", sub);
Output :
Substring: One
simple way to do this in one line of code would be this
string sub = input.Substring(input.Length > 5 ? input.Length - 5 : 0);
and here some informations about Operator ? :
string input = "OneTwoThree";
(if input.length >5)
{
string str=input.substring(input.length-5,5);
}
e.g.
string str = null;
string retString = null;
str = "This is substring test";
retString = str.Substring(8, 9);
This return "substring"
C# substring sample source
In C# 8.0 and later you can use [^5..] to get the last five characters combined with a ? operator to avoid a potential ArgumentOutOfRangeException.
string input1 = "0123456789";
string input2 = "0123";
Console.WriteLine(input1.Length >= 5 ? input1[^5..] : input1); //returns 56789
Console.WriteLine(input2.Length >= 5 ? input2[^5..] : input2); //returns 0123
index-from-end-operator and range-operator
// Get first three characters
string sub = input.Substring(0, 3);
Console.WriteLine("Substring: {0}", sub); // Output One.
string sub = input.Substring(6, 5);
Console.WriteLine("Substring: {0}", sub); //You'll get output: Three

Categories