deleting part of a string

조회 수: 17 (최근 30일)
andrew
andrew 2013년 7월 17일
댓글: arvind ramasamy 2018년 7월 11일
I have a string that I only want part of how do I get rid of the part I do not need.
for example:
original new
dogcat_1_12334 ==>dogcat
dogcat_2_13342 ==>dogcat
dogcat_3_13442 ==>dogcat

답변 (3개)

Jan
Jan 2013년 7월 17일
s = 'dogcat_1_12334';
t = strtok(s, '_');
  댓글 수: 1
arvind ramasamy
arvind ramasamy 2018년 7월 11일
I make a serial communication with an arduino and get the data of accelerometer mag and gyro values my data comes in as a string. 's' is the object i created for serial communication
data =fscanf(s,%s) % gives me the data from the arduino
i want my vector size to be 500. so when I run it in for loop
for i= 1:50
data =fscanf(s,'%s');
end
my output is: data = initializationsuccesful!
data = ax:123ay:23az:1234gx:23gy:50gz:43mx:23my:123mz:234
and goes on.
I use,
A_x(:,i) = str2num(data(:,4:8))
to get my vector. but since 'initializationsuccessful!' is not a number i am unable to form my vector. so how can I do it ???? this is my question

댓글을 달려면 로그인하십시오.


Evan
Evan 2013년 7월 17일
편집: Evan 2013년 7월 17일
Here's another answer, just in case the characters you want to keep don't fall in sequential order. If they don't, regexp with a "match" argument will split them up into separate cells. regexprep however, will just remove the unwanted parts.
ex1 = 'dogcat_1_12334'
ex2 = 'dog_1_12334_cat'
>> regexprep(ex1,'[^a-z]','')
ans =
dogcat
>> regexprep(ex2,'[^a-z]','')
ans =
dogcat
To modify this for more general cases, just change the string argument '[^a-z]'. Put any characters than you want to keep from being removed in the brackets []. The carat ^ operator specifies that "everything but" what is present in the brackets is modified to the second string argument, ''. Since '' is blank, that means anything not in the [^] will be removed.

Azzi Abdelmalek
Azzi Abdelmalek 2013년 7월 17일
편집: Azzi Abdelmalek 2013년 7월 17일
original='dogcat_1_12334'
new=regexp(str,'[a-z]+','match']
  댓글 수: 1
Azzi Abdelmalek
Azzi Abdelmalek 2013년 7월 17일
in case you have numbers and characters
new=regexp(str,'[a-z0-9]+','match','once')

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Whos에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by