How should I delete part of string from beginning to first space? - winforms

I'm using C++/CLI and I was trying to delete part of string from beginning to first space for a long time.
My code that doesn't work is:
String^ ns = gcnew String("Hello world!");
int temp1 = ns->IndexOf(" ");
int temp2 = ns->Length;
for (int i =temp1 +1; i < temp2; i++) {
ns+= ns[i];
}
What is the problem?

Why don't you count where is the first space, then use this function?
str = str->Remove( CoordsStart , CoordsEnd-CoordsStart );

You said from beginning to first space but it isn't what your program seems to be doing.
is :
String^ ns = gcnew String("Hello world!");
int temp1 = ns->IndexOf(" ");
for (int i = 0; i < temp1; i++) {
ns[&] = " ";
}
what you look for ?

Simple is best.
string ns ="Hello world!";
int temp1 = ns.IndexOf(" ") + 1;
ns = ns.Substring(temp1);
//Console.WriteLine(ns);

Related

Exception thrown at 0x7C131F4C (ucrtbased.dll) in ICP LAB ASSIGNMENT PROJECT.exe: 0xC0000005

I was trying to print some array but it won't print no matter what.
Which part did I do wrong?
Is it the array?
int main()
{
int i;
char id[3]; ///sample data wanted to print
id[0] = 'id1';
id[1] = 'id2';
id[2] = 'id3';
for (i = 1; i <= 3; ++i)
{
printf("%s", id[i]); ///The error appeared here////
}
}
i starts at 1, and goes to 3:
for (i = 1; i <= 3; ++i)
But you set up your array so that valid indicies are 0, 1, and 2.
3 is not a valid index.
Convention C-loops always look like this:
for(i = 0; i < 3; ++i)
That is, they start at 0 and go while less than the size of the array.
Not less than or equal to. That is your mistake.
Next, each element of the array is a single character.
But you are trying to initialize them with 3-letters, such as: id1.
A single character can hold ONE LETTER ONLY, not a set of 3 letters.
You are trying to print them out using %s; but %s is for strings, not single characters.
Here is a corrected version of your program.
int main()
{
int i;
char* id[3]; // Declare strings, not characters.
id[0] = "id1"; // Initialize each with a string
id[1] = "id2";
id[2] = "id3";
for (i = 0; i < 3; ++i) // Set loop limit correctly.
{
printf("%s\n", id[i]);
}
}
You invoked undefined behavior by passing data having wrong type: %s expects an pointer to a null-terminated string while you passed id[i], whose type is char (expanded to int here).
You can use %c to display the values of implementation-defined values of multi-character character literals.
Also The loop range is wrong as #abelenky says.
#include <stdio.h>
int main()
{
int i;
char id[3]; ///sample data wanted to print
id[0] = 'id1';
id[1] = 'id2';
id[2] = 'id3';
for (i = 0; i < 3; ++i)
{
printf("%c", id[i]);
}
}
Or do you mean this?
#include <stdio.h>
int main()
{
int i;
const char* id[3]; ///sample data wanted to print
id[0] = "id1";
id[1] = "id2";
id[2] = "id3";
for (i = 0; i < 3; ++i)
{
printf("%s\n", id[i]);
}
}

Split a char[] and store value in different arrays C

I´m new to C programming and have a problem:
I have a string:
char input[] = "1000 10 30: 1 2 3";
I want to split input and store value in different arrays, "1000 10 30" in one array and "1 2 3" in different array.
I've tried to use strtok(), but I can´t find the solution to do it.
Somebody know how to do it?
Thanks!
Edit: Thanks, here is rest of the code:
int a1[3];
int a2[3];
char input[] = "1000 10 30:400 23 123";
char*c = strtok(input, ":");
while (c != 0)
{
char* sep = strchr(c, ' ');
if (sep != 0)
{
*sep = 0;
a1[0] = atoi(c);
++sep;
*sep = strtok(sep, " ");
a1[1] = atoi(sep);
++sep;
a2[2] = atoi(sep);
}
c = strtok(0, ":");
I used an example I found here and tried to change it to add more element to an array, but could not make it. the third element is for some reason 0, and I don't understand why. I'm a beginner++ on programming, but mostly C# and I don't used pointers before.
It is unclear to me what you try to do with the pointer sep. And this code
*sep = strtok(sep, " ");
should give you compiler warnings as strtok returns a char pointer and you are trying to store it into a char (aka *sep).
You don't need more than strtok as you can give it multiple delimiters, i.e. you can give it both ' ' and ':' by passing it " :".
So the code could look like this:
int main() {
char input[] = "1000 10 30: 1 2 3";
int a1[3];
int a2[3];
int i = 0;
char* p = strtok(input, " :");
while(p)
{
if (i < 3)
{
a1[i] = atoi(p);
++i;
}
else if (i < 6)
{
a2[i-3] = atoi(p);
++i;
}
p = strtok(NULL, " :");
}
// Print the values
for (int j = 0; j <i; ++j)
{
if (j < 3)
{
printf("a1[%d] = %d\n", j, a1[j]);
}
else if (j < 6)
{
printf("a2[%d] = %d\n", j-3, a2[j-3]);
}
}
}
Output:
a1[0] = 1000
a1[1] = 10
a1[2] = 30
a2[0] = 1
a2[1] = 2
a2[2] = 3
Tip: The above code solves the task but I recommend you take a look at sscanf as it will allow you to read the values with a single line of code.

Trouble with a C "for" Loop - Won't iterate past 1st

I am working on a problem for CS50 in which I must create a pyramid out of #'s based on user input of a height. Here is what I have so far, but for height of 8, it only iterates once. For height of 7, I get about four lines of just a mess of #'s.
//Create GetPosInt() function
int GetPosInt(void) {
int n = GetInt();
while (n <= 0) {
printf("That won't work...\nRetry: ");
n = GetInt();
}
return n;
}
int main(void) {
printf("How high should Mario's pyramid be?\nHeight: ");
int h = GetPosInt();
while (h > 23) {
printf("Try something smaller!\nHeight: ");
h = GetPosInt();
}
char str[] = "##";
char strad[] = "#";
int l = h + 1;
for (int i = 0; i < h; i++) {
printf("%*s\n", l, str);
strcat(str, strad);
return 0;
}
}
This is my first attempt with the string.h library.
Please only tips on fixing my code - I'm certain there are other ways about it, but if it's possible this way, I'd like to keep it so for the class!
Your str array/C-String has no room to concatenate other chars than 2 chars.
As a little change you could do:
char str[128] = "";
strcat(str, "##");
Your return 0; is inside the loop, hence why. Edit as so:
for (int i = 0; i < h; i++) {
printf("%*s\n", l, str);
strcat(str, strad);
}
return 0;
In the C programming language you have to manage memory yourself. These memory allocations will not expand when you use strcat. Instead you will override memory beyond the memory allocated for str. I strongly suggest you first do an introduction into programming in C and how to manage memory manually.
You should return after the loop. You are leaving the function as soon as the first iteration finishes.
Also you should try defining str as :
char * str;
str = malloc( sizeof(char)* 2);
str = strcat(str, "##");
And using strcat as : str = strcat(str,strad);

Structure Array not printing correctly | C++

This is the structure
struct Student{
char firstName[MAX_LEN + 1];
char lastName[MAX_LEN + 1];
float gpa;
};
So let me say that StudentList1 has the correct data.
count Struct1 is how many names are entered.
Student StudentList1[10];
int count5 = 0, countfName = 0, countlName = 0;
while(count5 < countStruct1)
{
while(StudentList1[count5].firstName[countfName] != '\0')
{
StudentList2[count5].firstName[countfName] =
StudentList1[count5].firstName[countfName];
countfName++;
}
while(StudentList1[count5].lastName[countlName] != '\0')
{
StudentList2[count5].lastName[countlName] =
StudentList1[count5].lastName[countlName];
countlName++;
}
StudentList2[count5].gpa = StudentList1[count5].gpa;
count5++;
}
Now for some reason when I try this code, not using the arrays for characters of the last name and first name
while(count6 < count5)
{
cout << "Name: " << StudentList2[count6].firstName << " " << StudentList2[count6].lastName << "\n";
count6++;
}
Now when I try this doing it like this I just get a bunch of garbage, I get the first name printed but after that a whole bunch of garbage and the last name too but just garbage in between.
You're forgetting the terminating zero when you copy.
Since structs are copyable, you can do it like this:
while (count5 < countStruct1)
{
StudentList2[count5] = StudentList1[count5];
count5++;
}
or
for (int i = 0; i < countStruct1; i++)
{
StudentList2[i] = StudentList1[i];
}
which are slightly less error-prone.
In your code:
while(StudentList1[count5].firstName[countfName] != '\0')
{
StudentList2[count5].firstName[countfName] =
StudentList1[count5].firstName[countfName];
countfName++;
}
You have it stop when it hits the '\0', but you never re-write that '\0' to the end of the StudentList2
First, you need to copy the terminating zero:
StudentList2[count5].firstName[countfName] = '\0';
StudentList2[count5].lastName[countlName] = '\0';
then you need to reset your counters:
countfName = countlName = 0;
you should do this before the count5++ in your outermost while loop

Split String into String array

I have been playing around with programming for arduino but today i've come across a problem that i can't solve with my very limited C knowledge.
Here's how it goes.
I'm creating a pc application that sends serial input to the arduino (deviceID, command, commandparameters). This arduino will transmit that command over RF to other arduino's. depending on the deviceID the correct arduino will perform the command.
To be able to determine the deviceID i want to split that string on the ",".
this is my problem, i know how to do this easily in java (even by not using the standard split function), however in C it's a totally different story.
Can any of you guys tell me how to get this working?
thanks
/*
Serial Event example
When new serial data arrives, this sketch adds it to a String.
When a newline is received, the loop prints the string and
clears it.
A good test for this is to try it with a GPS receiver
that sends out NMEA 0183 sentences.
Created 9 May 2011
by Tom Igoe
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/SerialEvent
*/
String inputString; // a string to hold incoming data
boolean stringComplete = false; // whether the string is complete
String[] receivedData;
void setup() {
// initialize serial:
Serial.begin(9600);
// reserve 200 bytes for the inputString:
inputString.reserve(200);
}
void loop() {
// print the string when a newline arrives:
if (stringComplete) {
Serial.println(inputString);
// clear the string:
inputString = "";
stringComplete = false;
}
}
/*
SerialEvent occurs whenever a new data comes in the
hardware serial RX. This routine is run between each
time loop() runs, so using delay inside loop can delay
response. Multiple bytes of data may be available.
*/
void serialEvent() {
while (Serial.available()) {
// get the new byte:
char inChar = (char)Serial.read();
if (inChar == '\n') {
stringComplete = true;
}
// add it to the inputString:
if(stringComplete == false) {
inputString += inChar;
}
// if the incoming character is a newline, set a flag
// so the main loop can do something about it:
}
}
String[] splitCommand(String text, char splitChar) {
int splitCount = countSplitCharacters(text, splitChar);
String returnValue[splitCount];
int index = -1;
int index2;
for(int i = 0; i < splitCount - 1; i++) {
index = text.indexOf(splitChar, index + 1);
index2 = text.indexOf(splitChar, index + 1);
if(index2 < 0) index2 = text.length() - 1;
returnValue[i] = text.substring(index, index2);
}
return returnValue;
}
int countSplitCharacters(String text, char splitChar) {
int returnValue = 0;
int index = -1;
while (index > -1) {
index = text.indexOf(splitChar, index + 1);
if(index > -1) returnValue+=1;
}
return returnValue;
}
I have decided I'm going to use the strtok function.
I'm running into another problem now. The error happened is
SerialEvent.cpp: In function 'void splitCommand(String, char)':
SerialEvent:68: error: cannot convert 'String' to 'char*' for argument '1' to 'char* strtok(char*, const char*)'
SerialEvent:68: error: 'null' was not declared in this scope
Code is like,
String inputString; // a string to hold incoming data
void splitCommand(String text, char splitChar) {
String temp;
int index = -1;
int index2;
for(temp = strtok(text, splitChar); temp; temp = strtok(null, splitChar)) {
Serial.println(temp);
}
for(int i = 0; i < 3; i++) {
Serial.println(command[i]);
}
}
This is an old question, but i have created some piece of code that may help:
String getValue(String data, char separator, int index)
{
int found = 0;
int strIndex[] = {0, -1};
int maxIndex = data.length()-1;
for(int i=0; i<=maxIndex && found<=index; i++){
if(data.charAt(i)==separator || i==maxIndex){
found++;
strIndex[0] = strIndex[1]+1;
strIndex[1] = (i == maxIndex) ? i+1 : i;
}
}
return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
}
This function returns a single string separated by a predefined character at a given index. For example:
String split = "hi this is a split test";
String word3 = getValue(split, ' ', 2);
Serial.println(word3);
Should print 'is'. You also can try with index 0 returning 'hi' or safely trying index 5 returning 'test'.
Hope this help!
Implementation:
int sa[4], r=0, t=0;
String oneLine = "123;456;789;999;";
for (int i=0; i < oneLine.length(); i++)
{
if(oneLine.charAt(i) == ';')
{
sa[t] = oneLine.substring(r, i).toInt();
r=(i+1);
t++;
}
}
Result:
// sa[0] = 123
// sa[1] = 456
// sa[2] = 789
// sa[3] = 999
For dynamic allocation of memory, you will need to use malloc, ie:
String returnvalue[splitcount];
for(int i=0; i< splitcount; i++)
{
String returnvalue[i] = malloc(maxsizeofstring * sizeof(char));
}
You will also need the maximum string length.
The C way to split a string based on a delimiter is to use strtok (or strtok_r).
See also this question.
I think your idea is a good start point. Here is a code that i use (to parse HTTP GET REST requests with an Ethernet shield).
The idea is to use a while loop and lastIndexOf of and store the strings into an array (but your could do something else).
"request" is the string you want to parse (for me it was called request because.. it was).
int goOn = 1;
int count = -1;
int pos1;
int pos2 = request.length();
while( goOn == 1 ) {
pos1 = request.lastIndexOf("/", pos2);
pos2 = request.lastIndexOf("/", pos1 - 1);
if( pos2 <= 0 ) goOn = 0;
String tmp = request.substring(pos2 + 1, pos1);
count++;
params[count] = tmp;
// Serial.println( params[count] );
if( goOn != 1) break;
}
// At the end you can know how many items the array will have: count + 1 !
I have used this code successfully, but i thing their is an encoding problem when i try to print params[x]... i'm alos a beginner so i don't master chars vs string...
Hope it helps.
I believe this is the most straight forward and quickest way:
String strings[10]; // Max amount of strings anticipated
void setup() {
Serial.begin(9600);
int count = split("L,-1,0,1023,0", ',');
for (int j = 0; j < count; ++j)
{
if (strings[j].length() > 0)
Serial.println(strings[j]);
}
}
void loop() {
delay(1000);
}
// string: string to parse
// c: delimiter
// returns number of items parsed
int split(String string, char c)
{
String data = "";
int bufferIndex = 0;
for (int i = 0; i < string.length(); ++i)
{
char c = string[i];
if (c != ',')
{
data += c;
}
else
{
data += '\0';
strings[bufferIndex++] = data;
data = "";
}
}
return bufferIndex;
}

Resources