When I run this through the debugger the result for string CL_S and string NA_S are the same value, which is 122.13.
Not sure why it does this since the indexOf is different - the second one does not exist.
text = "4R|1|^^^100^CL_S|122.13|38||||F|||20070628114638"
string str = text;
try
{
int a_first = str.IndexOf("^^^100") + "^^^100".Length + 1;
string str_a = str.Substring(a_first);
string[] words_a = str_a.Split('|');
string CL_S = words_a[1];
int b_first = str.IndexOf("^^^101") + "^^^101".Length + 1;
string str_b = str.Substring(b_first);
string[] words_b = str_b.Split('|');
string NA = words_b[1];
Step through a debugger and look at the values of the variables.
Here's a quick analysis which should help point you towards the problem:
a_first has the value 12
str_a has the value "CLS_S|122.13|..."
b_first has the value 6 (Note that you are adding -1 + 6 + 1; the -1 is from the IndexOf that doesn't have a match. IndexOf is working just fine.)
str_b has the value "^^100^CL_S|122.13|..."
When you split either str_a or str_b on a |, the second element (index [1]) of both will be 122.13.
In the second case the IndexOf call returns -1, and adding seven to that puts you at index 6.
When you use that in the Substring call you will get ^^100^ prefixed to the string, compared to the string from the first case.
As that doesn't contain any | characters, splitting will only give a different result for the first item in the array, and as you are getting the second item it will be the same as in the first case.
Run this on IDEONE https://ideone.com/F6KDNS
using System;
public class Test
{
public static void Main()
{
string str = "4R|1|^^^100^CL_S|122.13|38||||F|||20070628114638" ;
int a_first = str.IndexOf("^^^100") + "^^^100".Length + 1;
string str_a = str.Substring(a_first);
string[] words_a = str_a.Split('|');
string CL_S = words_a[1];
Console.WriteLine(a_first);
Console.WriteLine(str_a);
Console.WriteLine(CL_S);
Console.WriteLine();
int b_first = str.IndexOf("^^^101") + "^^^101".Length + 1;
string str_b = str.Substring(b_first);
string[] words_b = str_b.Split('|');
string NA = words_b[1];
Console.WriteLine(b_first);
Console.WriteLine(str_b);
Console.WriteLine(NA);
}
}
I got this:
12
CL_S|122.13|38||||F|||20070628114638
122.13
6
^^100^CL_S|122.13|38||||F|||20070628114638
122.13
So you can see that the second IndexOf returns -1 => b_first is 6. This means that you the two strings in both have their first break at
CL_S| & ^^100^CL_S|
And thus both have second item = 122.13
Related
Please check variable "mystr" value where a "-" sign between two part of numbers. I want to find "-" then remove all character after that then I want find same "-" and remove all Character from first to till that. I know it's simple but not getting exact solution on c# due to I am new.
public void test()
{
string mystr = "1.30-50.50";
//first output I want is- "1.30"
//second output I want is- "50.50"
}
Use string.Split method:
var mystr = "1.30-50.50";
var result = mystr.Split('-');
var a = result[0]; //"1.30"
var b = result[1]; //"50.50"
you can also String.IndexOf method
string mystr = "1.30-50.50";
int indexOfDash = mystr.IndexOf('-');
string firsResult = mystr.Substring(0, indexOfDash);
string secondResult = mystr.Substring(indexOfDash + 1, mystr.Length - indexOfDash - 1);
I have a string like AX_1234X_12345_X_CXY, I want to remove X from after the first underscore _ i.e. from 1234X to 1234. So final output will be like AX_1234_12345_X_CXY. How to do it?? If I use .Replace("X", "") it will replace all X which I don't want
You can iterate trough the string from the first occurrence of '_' .
you can find the first occurrence of '_' using IndexOf().
when loop will get to 'X' it will not append it to the "fixed string".
private static void Func()
{
string Original = "AX_1234X_12345_X_CXY";
string Fixed = Original.Substring(0, Original.IndexOf("_", 0));
// in case you want to remove all 'X`s' after first occurrence of `'_'`
// just dont use that variable
bool found = false;
for (int i = Original.IndexOf("_", 0); i < Original.Length; i++)
{
if (Original[i].ToString()=="X" && found == false)
{
found = true;
}
else
{
Fixed += Original[i];
}
}
Console.WriteLine(Fixed);
Console.ReadLine();
}
Why not good old IndexOf and Substring?
string s = "AX_1234X_12345_X_CXY";
int pUnder = s.IndexOf('_');
if (pUnder >= 0) { // we have underscope...
int pX = s.IndexOf('X', pUnder + 1); // we should search for X after the underscope
if (pX >= 0) // ...as well as X after the underscope
s = s.Substring(0, pX) + s.Substring(pX + 1);
}
Console.Write(s);
Outcome:
AX_1234_12345_X_CXY
string original = #"AX_1234X_12345_X_CXY";
original = #"AX_1234_12345_X_CXY";
One way is String.Remove, because you can tell exactly where to remove from. If the offending "X" is always in the same place, you can use:
string newString = old.Remove(7,1);
This will remove 1 character starting as position 7 (counting from zero as the beginning of the string).
If not always in the same character position, you might try:
int xPos = old.IndexOf("X");
string newString = old.Remove(xPos,1);
EDIT:
Based on OP comment, the "X" we're targeting occurs just after the first underscore character, so let's index off of the first underscore:
int iPosUnderscore = old.IndexOf("_");
string newString = old.Remove(iPosUnderscore + 1 ,1); // start after the underscore
Try looking at string.IndexOf or string.IndexOfAny
string s = "AX_1234X_12345_X_CXY";
string ns = HappyChap(s);
public string HappyChap(string value)
{
int start = value.IndexOf("X_");
int next = start;
next = value.IndexOf("X_", start + 1);
if (next > 0)
{
value = value.Remove(next, 1);
}
return value;
}
If and only if this is always the format then it should be a simple matter of combining substrings of the original text without including the x in that position. But the op hasn't stated that this is always the case. So if this is always the format and the same character position is always removed then you could simply just
string s = "AX_1234X_12345_X_CXY";
string newstring = s.Substring(0, 7) + s.Substring(8);
OK, based on only the second set of numbers being variable in length, you could then do something like:
int startpos = s.IndexOf('_', 4);
string newstring = s.Substring(0, startpos - 1) + s.Substring(startpos);
with this code, the following tests resulted in:
"AX_1234X_12345_X_CXY" became "AX_1234_12345_X_CXY"
"AX_123X_12345_X_CXY" became "AX_123_12345_X_CXY"
"AX_234X_12345_X_CXY" became "AX_234_12345_X_CXY"
"AX_1X_12345_X_CXY" became "AX_1_12345_X_CXY"
Something like this could work. I'm sure there's a more elegant solution.
string input1 = "AX_1234X_12345_X_CXY";
string pattern1 = "^[A-Z]{1,2}_[0-9]{1,4}(X)";
string newInput = string.Empty;
Match match = Regex.Match(input1, pattern1);
if(match.Success){
newInput = input1.Remove(match.Groups[1].Index, 1);
}
Console.WriteLine(newInput);
I have strings that look like this:
1.23.4.34
12.4.67
127.3.2.21.3
1.1.1.9
This is supposed to be a collection of numbers, separated by '.' symbols, similar to an ip address. I need to increment only the last digit/digits.
Expected Output:
1.23.4.35
12.4.68
127.3.2.21.4
1.1.1.10
Basically, increment whatever the number that is after the last '.' symbol.
I tried this:
char last = numberString[numberString.Length - 1];
int number = Convert.ToInt32(last);
number = number + 1;
If I go with the above code, I just need to replace the characters after the last '.' symbol with the new number. How do I get this done, good folks? :)
It seems to me that one method would be to:
split the string on . to get an array of components.
turn the final component into an integer.
increment that integer.
turn it back into a string.
recombine the components with . characters.
See, for example, the following program:
using System;
namespace ConsoleApplication1 {
class Program {
static void Main(string[] args) {
String original = "1.23.4.34";
String[] components = original.Split('.');
int value = Int32.Parse(components[components.Length - 1]) + 1;
components[components.Length - 1] = value.ToString();
String newstring = String.Join(".",components);
Console.WriteLine(newstring);
}
}
}
which outputs the "next highest" value of:
1.23.4.35
You can use string.LastIndexOf().
string input = "127.3.2.21.4";
int lastIndex = input.LastIndexOf('.');
string lastNumber = input.Substring(lastIndex + 1);
string increment = (int.Parse(lastNumber) + 1).ToString();
string result = string.Concat(input.Substring(0, lastIndex + 1), increment);
You need to extract more than just the last character. What if the last character is a 9 and then you add 1 to it? Then you need to correctly add one to the preceding character as well. For example, the string 5.29 should be processed to become 5.30 and not simply 5.210 or 5.20.
So I suggest you split the string into its number sections. Parse the last section into an integer. Increment it and then create the string again. I leave it as an exercise for the poster to actually write the few lines of code. Good practice!
Something like this:
var ip = "1.23.4.34";
var last = int.Parse(ip.Split(".".ToCharArray(),
StringSplitOptions.RemoveEmptyEntries).Last());
last = last + 1;
ip = string.Format("{0}.{1}",ip.Remove(ip.LastIndexOf(".")) , last);
If you are dealing with IP, there will be some extra code in case of .034, which should be 035 instead of 35. But that logic is not that complicated.
It's simple as this, use Split() and Join() String methods
String test = "1.23.4.34"; // test string
String[] splits = test.Split('.'); // split by .
splits[splits.Length - 1] = (int.Parse(splits[splits.Length - 1])+1).ToString(); // Increment last integer (Note : Assume all are integers)
String answ = String.Join(".",splits); // Use string join to make the string from string array. uses . separator
Console.WriteLine(answ); // Answer : 1.23.4.35
Using a bit of Linq
int[] int_arr = numberString.Split('.').Select(num => Convert.ToInt32(num)).ToArray();
int_arr[int_arr.Length - 1]++;
numberString = "";
for(int i = 0; i < int_arr.Length; i++) {
if( i == int_arr.Length - 1) {
numberString += int_arr[i].ToString();
}
else {
numberString += (int_arr[i].ToString() + ".");
}
}
Note: on phone so can't test.
My Solution is:
private static string calcNextCode(string value, int index)
{
if (value is null) return "1";
if (value.Length == index + 1) return value + "1";
int lastNum;
int myIndex = value.Length - ++index;
char myValue = value[myIndex];
if (int.TryParse(myValue.ToString(), NumberStyles.Integer, null, out lastNum))
{
var aStringBuilder = new StringBuilder(value);
if (lastNum == 9)
{
lastNum = 0;
aStringBuilder.Remove(myIndex, 1);
aStringBuilder.Insert(myIndex, lastNum);
return calcNextCode(aStringBuilder.ToString(), index++);
}
else
{
lastNum++;
}
aStringBuilder.Remove(myIndex, 1);
aStringBuilder.Insert(myIndex, lastNum);
return aStringBuilder.ToString();
}
return calcNextCode(value, index++);
}
I have a string like this: C:\Projects\test\whatever\files\media\10\00\00\80\test.jpg
Now, what I want to do is to dynamically combine the last 4 numbers, in this case its 10000080 as result. My idea was ti split this and combine them in some way, is there an easier way? I cant rely on the array index, because the path can be longer or shorter as well.
Is there a nice way to do that?
Thanks :)
A compact way using string.Join and Regex.Split.
string text = #"C:\Projects\test\whatever\files\media\10\00\00\80\test.jpg";
string newString = string.Join(null, Regex.Split(text, #"[^\d]")); //10000080
Use String.Split
String toSplit = "C:\Projects\test\whatever\files\media\10\00\00\80\test.jpg";
String[] parts = toSplit.Split(new String[] { #"\" });
String result = String.Empty;
for (int i = 5, i > 1; i--)
{
result += parts[parts.Length - i];
}
// Gives the result 10000080
You can rely on array index if the last part always is the filename.
since the last part is always
array_name[array_name.length - 1]
the 4 parts before that can be found by
array_name[array_name.length - 2]
array_name[array_name.length - 3]
etc
If you always want to combine the last four numbers, split the string (use \ as the separator), start counting from the last part and take 4 numbers, or the 4 almost last parts.
If you want to take all the digits, just scan the string from start to finish and copy just the digits to a new string.
string input = "C:\Projects\test\whatever\files\media\10\00\00\80\test.jpg";
string[] parts = toSplit.Split(new char[] {'\\'});
IEnumerable<string> reversed = parts.Reverse();
IEnumerable<string> selected = reversed.Skip(1).Take(4).Reverse();
string result = string.Concat(selected);
The idea is to extract the parts, reverse them to keep only the last 4 (excluding the file name) and re reversing to rollback to the initial order, then concat.
Using LINQ:
string path = #"C:\Projects\test\whatever\files\media\10\00\00\80\test.jpg";
var parts = Path.GetDirectoryName(path).Split('\\');
string numbersPart = parts.Skip(parts.Count() - 4)
.Aggregate((acc, next) => acc + next);
Result: "10000080"
var r = new Regex(#"[^\d+]");
var match = r
.Split(#"C:\Projects\test\whatever\files\media\10\00\00\80\test.jpg")
.Aggregate((i, j) => i + j);
return match.ToString();
to find the number you can use regex:
(([0-9]{2})\\){4}
use concat all inner Group ([0-9]{2}) to get your searched number.
This will always find your searched number in any position in the given string.
Sample Code:
static class TestClass {
static void Main(string[] args) {
string[] tests = { #"C:\Projects\test\whatever\files\media\10\00\00\80\test.jpg",
#"C:\Projects\test\whatever\files\media\10\00\00\80\some\foldertest.jpg",
#"C:\10\00\00\80\test.jpg",
#"C:\10\00\00\80\test.jpg"};
foreach (string test in tests) {
int number = ExtractNumber(test);
Console.WriteLine(number);
}
Console.ReadLine();
}
static int ExtractNumber(string path) {
Match match = Regex.Match(path, #"(([0-9]{2})\\){4}");
if (!match.Success) {
throw new Exception("The string does not contain the defined Number");
}
//get second group that is where the number is
Group #group = match.Groups[2];
//now concat all captures
StringBuilder builder = new StringBuilder();
foreach (var capture in #group.Captures) {
builder.Append(capture);
}
//pares it as string and off we go!
return int.Parse(builder.ToString());
}
}
this might be simple question I have 3 strings
A123949DADWE2ASDASDW
ASDRWE234DS2334234234
ZXC234ASD43D33SDF23SDF
I want to split those by the first 8 characters and then the 10th and 11th and then combine them into one string.
So I would get:
A123949DWE
ASDRWE23S2
ZXC234AS3D
Basically the 9th character and anything after the 12th character is removed.
You can use String.Substring:
s = s.Substring(0, 8) + s[10] + s[11]
Example code:
string[] a = {
"A123949DADWE2ASDASDW",
"ASDRWE234DS2334234234",
"ZXC234ASD43D33SDF23SDF"
};
a = a.Select(s => s.Substring(0, 8) + s[10] + s[11]).ToArray();
Result:
A123949DWE
ASDRWE23S2
ZXC234AS3D
So let's say you have them declared as string variables:
string s1 = "A123949DADWE2ASDASDW";
string s2 = "ASDRWE234DS2334234234";
string s3 = "ZXC234ASD43D33SDF23SDF";
You can use the substring to get what you want:
string s1substring = s1.Substring(0,8) + s1.Substring(9,2);
string s2substring = s1.Substring(0,8) + s1.Substring(9,2);
string s3substring = s1.Substring(0,8) + s1.Substring(9,2);
And that should give you what you need. Just remember, that the string position is zero-based so you'll have to subtract one from the starting position.
So you could do:
string final1 = GetMyString("A123949DADWE2ASDASDW");
string final2 = GetMyString("ASDRWE234DS2334234234");
string final3 = GetMyString("ZXC234ASD43D33SDF23SDF");
public function GetMyString(string Original)
{
string result = Original.Substring(12);
result = result.Remove(9, 1);
return result;
}