Unable to Split the string accordingly - c#

I know this question would have been asked infinite number of times, but I'm kinda stuck.
I have a string something like
"Doc1;Doc2;Doc3;12"
it can be something like
"Doc1;Doc2;Doc3;Doc4;Doc5;56"
Its like few pieces of strings separated by semicolon, followed by a number or id.
I need to extract the number/id and the strings separately.
To be exact, I can have 2 strings: one having "Doc1;Doc2;Doc3" or "Doc1;Doc2;Doc3;Doc4" and the other having just the number/id as "12" or "34" or "45" etc.
And yeah I am using C# 3.5
I understand its a pretty easy and witty question, but this guy is stuck.
Assistance required from experts.
Regards
Anurag

string.LastIndexOf and string.Substring are the keys to what you're trying to do.
var str = "Doc1;Doc2;Doc3;12";
var ind = str.LastIndexOf(';');
var str1 = str.Substring(0, ind);
var str2 = str.Substring(ind+1);

One way:
string[] tokens = str.Split(';');
var docs = tokens.Where(s => s.StartsWith("Doc", StringComparison.OrdinalIgnoreCase));
var numbers = tokens.Where(s => s.All(Char.IsDigit));

String docs = s.Substring(0, s.LastIndexOf(';'));
String number = s.Substring(s.LastIndexOf(';') + 1);

One possible approach would be this:
var ids = new List<string>();
var nums = new List<string>();
foreach (var s in input.Split(';'))
{
int val;
if (!int.TryParse(s, out val)) { ids.Add(s); }
else { nums.Add(s); }
}
where input is something like Doc1;Doc2;Doc3;Doc4;Doc5;56. Now, ids will house all of the Doc1 like values and nums will house all of the 56 like values.

you can use StringTokenizer functionality.
http://www.c-sharpcorner.com/UploadFile/pseabury/JavaLikeStringTokenizer11232005015829AM/JavaLikeStringTokenizer.aspx
split string using ";"
StringTokenizer st = new StringTokenizer(src1,";");
collect final String. that will be your ID.

You may try one of two options: (assuming your input string is in string str;
Approach 1
Get LastIndexOf(';')
Split the string based on the index. This will give you string and int part.
Split the string part and process it
Process the int part
Approach 2
Split the string on ;
Run a for loop - for (int i = 0; i < str.length - 2; i++) - this is the string part
Process str[length - 1] separately - this is the int part
Please take this as a starting point as there could be other approaches to implement a solution for this

string actual = "Doc1;Doc2;Doc3;12";
int lstindex = actual.LastIndexOf(';');
string strvalue = actual.Substring(0, lstindex);
string id = actual.Substring(lstindex + 1);

Related

Sorting a given string - What is wrong with my IF Contains block?

Super new to C# apologize upfront. My goal is to sort a given string. Each word in the string will contain a single number. This number is the position the word should have in the result. Numbers can be from 1 to 9. So 1 will be the first word (not 0).
My plan of attack is to split the string, having one variable of int data-type (int lookingForNum) and the other variable turning that into a String data-type(string stringLookingForNum), then for each loop over the array looking to see if any elements contain string stringLookingForNum, if they do I add it to an emptry string variable, lastly add 1 to int variable lookingForNum. My issue seems to be with the if statement with the Contains method. It will not trigger the way I currently have it written. Hard coding in if (word.Contains("1")) will trigger that code block but running it as written below will not trigger the if statement.Please can anyone tell my WHY!?!? I console.log stringLookingForNum and it is for sure a string data type "1"
This noobie would appreciate any help. Thanks!
string testA = "is2 Thi1s T4est 3a"; //--> "Thi1s is2 3a T4est"
string[] arrayTestA = testA.Split(' ');
string finalString = string.Empty;
int lookingForNum = 1; //Int32
foreach (string word in arrayTestA){
string stringLookingForNum = lookingForNum.ToString();
//Don't understand why Contains is not working as expected here)
if (word.Contains(stringLookingForNum)){
finalString = finalString + $"{word} ";
}
lookingForNum++;
}
you need this - look for the string with 1, the look for the string with 2 etc. Thats not what you are doing
you look at the first string and see if it contains one
then look at the second one and see if it contains 2
....
int lookingForNum = 1;
while(true){ // till the end
string stringLookingForNum = lookingForNum.ToString();
bool found = false;
foreach (string word in arrayTestA){
if (word.Contains(stringLookingForNum)){
finalString = finalString + $"{word} ";
found = true;
break;
}
}
if(!found) break;
lookingForNum++;
}
To sort you should simply use OrderBy, and since you need to sort by number inside a word - just Find and extract a number from a string
string testA = "is2 Thi1s T4est 3a";
var result = testA.Split().OrderBy(word =>
Int32.Parse(Regex.Match(word, #"\d+").Value));
Console.WriteLine(string.Join(" ", result));

How to remove an element from a split String?

I'm trying to remove an element/item/entry from a split string.
Let's say I got the string [string_] as follows:
string string_ = "one;two;three;four;five;six";
Then I split this string to get each, let's say, item:
string[] item = (string_.Split(";"));
I have no informations other than from variables. Depending on the user choice, I can get an item value and index.
Let's say that for this example, the user chose "four" which is the index "3".
How can I make my string look like the index 3 have been deleted, as string_ would be equal to the following:
"one;two;three;five;six"
I've tried multiple things and it seems like the only solution is to go through a char method.
Is that true or did I miss something?
EDIT to suggested already_posted_answer :
Not quite the same question as my ITEM could be placed anywhere in my splitted string depending on the user selection.
First of all you need to write better variable names, string_ is a horrible name. Even something like "input" is way better.
string input = "one;two;three;four;five;six";
Next, you are on the right track by using Split(). This will return an array of string:
string[] splitInput = input.Split(";");
The resulting string array will look like this:
//string[0] = one
//string[1] = two
//string[2] = three
//string[3] = four
//string[4] = five
//string[5] = six
Removing with known index
If you want to remove a specific element from the array, you could make the result of Split() a List<T> by using ToList() instead and utilize the RemoveAt() method of the resulting List<T>:
List<string> splitList = input.Split(';').ToList();
splitList.RemoveAt(3);
//Re-create the string
string outputString = string.Join(";", splitList);
//output is: "one;two;three;five;six"
Remove all strings that match an input
If you need to remove items from the list without knowing their index but knowing the actual string, you can use LINQ's Where() to filter out the matching items:
//Get the input from the user somehow
string userInput = Console.ReadLine();
IEnumerable<string> filteredList = input.Split(';')
.Where(x => string.Compare(x, userInput, true) != 0);
//Re-create the string
string outputString = string.Join(";", filteredList);
I made a fiddle to demonstrate both methods here
You can convert an array of string to list by following:
var list = new List<string>(item);
Once the list is created, you can easily remove an element:
var index = list.IndexOf("four");
list.RemoveAt(index);
Join the string back:
var result = String.Join(";", list.ToArray());
Result:
You can convert your string array into a List<string>, and since you have the index of the item to be removed, you can remove the item using RemoveAt, then join the items back into one string.
Here's a complete console application example:
static void Main(string[] args)
{
string string_ = "one;two;three;four;five;six";
string[] items = (string_.Split(';'));
Console.WriteLine("Please select an item to remove:");
for (int i = 0;i<items.Length;i++)
{
Console.WriteLine(string.Format("{0}- {1}", (i + 1).ToString(), items[i]));
}
int num = 0;
int.TryParse(Console.ReadLine(), out num);
if (num > 0 && num <= items.Length)
{
List<string> itemsList = items.ToList();
itemsList.RemoveAt(num - 1);
string newString = string.Join(";", itemsList);
Console.WriteLine(string.Format("The new string is: {0}", newString));
}
else
{
Console.WriteLine("Invalid number!");
}
Console.ReadLine();
}
Hope that helps.
We can employ LINQ.
Initial plan is to split the string, then create a union of two enumerables: before and after the item. Something like this:
// preconditions
const int idx = 3;
string string_ = "one;two;three;four;five;six";
// actual transformation
string[] item = (string_.Split(';'));
var iterator = item.Take(idx).Concat(item.Skip(idx + 1));
// output the results
var result = string.Join(";", iterator);
Console.Write(result);
Would this work for you?
If you create a new string like this, then replace the value of string_ with the value of the new string.
string string_ = "one;two;three;four;five;six";
string newstring = string_.Replace("four", "");
string_ = newstring.Replace(";;", ";");

how to get text after a certain comma on C#?

Ok guys so I've got this issue that is driving me nuts, lets say that I've got a string like this "aaa,bbb,ccc,ddd,eee,fff,ggg" (with out the double quotes) and all that I want to get is a sub-string from it, something like "ddd,eee,fff,ggg".
I also have to say that there's a lot of information and not all the strings look the same so i kind off need something generic.
thank you!
One way using split with a limit;
string str = "aaa,bbb,ccc,ddd,eee,fff,ggg";
int skip = 3;
string result = str.Split(new[] { ',' }, skip + 1)[skip];
// = "ddd,eee,fff,ggg"
I would use stringToSplit.Split(',')
Update:
var startComma = 3;
var value = string.Join(",", stringToSplit.Split(',').Where((token, index) => index > startComma));
Not really sure if all things between the commas are 3 length. If they are I would use choice 2. If they are all different, choice 1. A third choice would be choice 2 but implement .IndexOf(",") several times.
Two choices:
string yourString="aaa,bbb,ccc,ddd,eee,fff,ggg";
string[] partsOfString=yourString.Split(','); //Gives you an array were partsOfString[0] is "aaa" and partsOfString[1] is "bbb"
string trimmed=partsOfString[3]+","+partsOfString[4]+","+partsOfString[5]+","+partsOfSting[6];
OR
//Prints "ddd,eee,fff,ggg"
string trimmed=yourString.Substring(12,14) //Gets the 12th character of your string and goes 14 more characters.

How to get the next word in a string?

I feel pretty foolish for asking a seemingly easy question Sigh but for the life of me I cant figure it out.
string myString = "10/27/14 TheNextString DontWantThisString";
Assume that the second string is unknown(as in it could be any type of word). How could I get the second word after the last index of the date.
Sorry this Is probably a weird question.
var lastLine = line.Substring(idx + "date:".Length + 1, 14);
var lastChar = lastLine.Substring(lastLine.Length-1, 1);
headerName = lastLine.Substring(lastLine.LastIndexOf(lastChar), +1);
Heres some of my code for a little context if you will.
You want String.Split().
string[] delimiters = new string[] {" "};
string[] words = myString.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
string myString = "10/27/14 TheNextString DontWantThisString";
var values = Regex.Split(myString , #"\s+");
if (values.Count > 1)
Console.WriteLine(values[1]);
This should work (haven't tested the code, but you get the idea).
String result[] = myString.split(null);
result[1] will return what you need.
See: String.SplitMethod
namespace SplitDemo
{
class Program
{
static void Main(string[] args)
{
var myString = "10/27/14 TheNextString DontWantThisString";
var stringArray = myString.Split(default(char[]), StringSplitOptions.RemoveEmptyEntries);
var word = stringArray[1];
}
}
}
Something like this should work for you. This splits the string into an array, using a space as the separator, removes any empty matches, and then gets the second item.
myString.Split(new[]{' '}, StringSplitOptions.RemoveEmptyEntries)[1]
http://msdn.microsoft.com/en-us/library/ms131448.aspx

C# Best way to retrieve strings that's in quotation mark?

Suppose I am given a following text (in a string array)
engine.STEPCONTROL("00000000","02000001","02000043","02000002","02000007","02000003","02000008","02000004","02000009","02000005","02000010","02000006","02000011");
if("02000001" == 1){
dimlevel = 1;
}
if("02000001" == 2){
dimlevel = 3;
}
I'd like to extract the strings that's in between the quotation mark and put it in a separate string array. For instance, string[] extracted would contain 00000000, 02000001, 02000043....
What is the best approach for this? Should I use regular expression to somehow parse those lines and split it?
Personally I don't think a regular expression is necessary. If you can be sure that the input string is always as described and will not have any escape sequences in it or vary in any other way, you could use something like this:
public static string[] ExtractNumbers(string[] originalCodeLines)
{
List<string> extractedNumbers = new List<string>();
string[] codeLineElements = originalCodeLines[0].Split('"');
foreach (string element in codeLineElements)
{
int result = 0;
if (int.TryParse(element, out result))
{
extractedNumbers.Add(element);
}
}
return extractedNumbers.ToArray();
}
It's not necessarily the most efficient implementation but it's quite short and its easy to see what it does.
that could be
string data = "\"00000000\",\"02000001\",\"02000043\"".Replace("\"", string.Empty);
string[] myArray = data.Split(',');
or in 1 line
string[] data = "\"00000000\",\"02000001\",\"02000043\"".Replace("\"", string.Empty).Split(',');

Categories

Resources